Thread parameters – what not to do

The really key thing to keep in mind when passing a parameter to a thread routine is that you must guarantee that the parameter passed along is thread-safe; essentially, that it does not get modified in any manner while a thread (or threads) are using it.

(Thread safety is a crucial aspect of working with threads; we shall revisit this point often in upcoming chapters, too).

To help understand the possible issues clearly, let's take a couple of typical examples. In the first one, we shall (attempt to) pass the loop index as the parameter to the newly born thread such as, in main (code: ch14/pthreads1_wrong.c):

 printf("main: &i=%p\n", &i); for (i = 0; i < NTHREADS; i++) { printf("Creating thread #%ld now ...

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.