Making code thread-safe

Obviously, we would prefer to make the testit function thread-safe. Now the question becomes, how exactly can we do that? Well, again, it's quite straightforward: there are two approaches (more than two, actually, but we'll get to that later).

If we can eliminate any and all global shared writable data in the code path, we will have no critical sections and no problem; in other words, it will become thread-safe. So, one way to achieve this is to ensure that the function uses only local (automatic) variables. The function is now reentrant safe. Before proceeding further, it's important to understand some key points regarding reentrant and thread safety.

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.