Saturday, June 13, 2015

Thread-Specific Data API

Last time it was making function thread safe or reentrant via thread local storage, now more complicated thread-specific data. Everything happens on Linux but should be applicable on any UNIX since we are using POSIX.
This one is also called thread-private data API. It creates per thread and per reentrant function storage. Process starts with key creation when thread for the first time calls function, any thread. In order to have key created once pthread_once is used. Then, once we got key, pthread_getspecific and pthread_setspecific are used to deal with thread-specific data. Here is example:


To compile it the following is used:

gcc -o tsdexample tsdexample.c -pthread

Result of execution is:

Main message: Message is 'Hello from main!'
From thread: Message is 'Hello I am lumberjack!'
Again thread: Message is 'Hello I am lumberjack!'
Main message: Message is 'I am not lumberjack!'


In order to init static variable once, macro  PTHREAD_ONCE_INIT is used. During key creation destructor, ordinary free, is passed as parameter to pthread_key_create. Main thread and another thread then are calling reentrant function and setting and retrieving messages which are thread specific, what is expected. If we want to delete key it looks like this:


Though in example program it is static variable and it will go out of scope together with program.

No comments:

Post a Comment