1 /* Making a library function that uses static variables thread-safe.
2 Illustrates: thread-specific data, pthread_once(). */
10 /* This is a typical example of a library function that uses
11 static variables to accumulate results between calls.
12 Here, it just returns the concatenation of all string arguments
13 that were given to it. */
18 str_accumulate (char *s
)
20 static char accu
[1024] = { 0 };
27 /* Of course, this cannot be used in a multi-threaded program
28 because all threads store "accu" at the same location.
29 So, we'll use thread-specific data to have a different "accu"
32 /* Key identifying the thread-specific data */
33 static pthread_key_t str_key
;
34 /* "Once" variable ensuring that the key for str_alloc will be allocated
36 static pthread_once_t str_alloc_key_once
= PTHREAD_ONCE_INIT
;
38 /* Forward functions */
39 static void str_alloc_key (void);
40 static void str_alloc_destroy_accu (void *accu
);
42 /* Thread-safe version of str_accumulate */
45 str_accumulate (const char *s
)
49 /* Make sure the key is allocated */
50 pthread_once (&str_alloc_key_once
, str_alloc_key
);
51 /* Get the thread-specific data associated with the key */
52 accu
= (char *) pthread_getspecific (str_key
);
53 /* It's initially NULL, meaning that we must allocate the buffer first. */
60 /* Store the buffer pointer in the thread-specific data. */
61 pthread_setspecific (str_key
, (void *) accu
);
62 printf ("Thread %lx: allocating buffer at %p\n", pthread_self (), accu
);
64 /* Now we can use accu just as in the non thread-safe code. */
69 /* Function to allocate the key for str_alloc thread-specific data. */
74 pthread_key_create (&str_key
, str_alloc_destroy_accu
);
75 printf ("Thread %lx: allocated key %d\n", pthread_self (), str_key
);
78 /* Function to free the buffer when the thread exits. */
79 /* Called only when the thread-specific data is not NULL. */
82 str_alloc_destroy_accu (void *accu
)
84 printf ("Thread %lx: freeing buffer at %p\n", pthread_self (), accu
);
94 res
= str_accumulate ("Result of ");
95 res
= str_accumulate ((char *) arg
);
96 res
= str_accumulate (" thread");
97 printf ("Thread %lx: \"%s\"\n", pthread_self (), res
);
102 main (int argc
, char **argv
)
107 res
= str_accumulate ("Result of ");
108 pthread_create (&th1
, NULL
, process
, (void *) "first");
109 pthread_create (&th2
, NULL
, process
, (void *) "second");
110 res
= str_accumulate ("initial thread");
111 printf ("Thread %lx: \"%s\"\n", pthread_self (), res
);
112 pthread_join (th1
, NULL
);
113 pthread_join (th2
, NULL
);