- Unlike processes, all threads in a single program share the same address space. This means that if one thread modifies a location in memory, the change is visible to all other threads.
- This allows multiple threads to operate on the same data without the use interprocess communication mechanisms.
- Each thread has its own call stack, however. As in a single-threaded program, each invocation of a subroutine in each thread has its own set of local variables, which are stored on the stack for that thread.
- Sometimes, however, it is desirable to duplicate a certain variable so that each thread has a separate copy (thread-specific data area). The variables stored in this area are duplicated.
- Special functions for setting and retrieving values from the thread-specific data area.
- You may create as many thread-specific data items as you want, each of type void*.
- Each item is referenced by a key. To create a new key, and thus a new data item for each thread, use pthread_key_create.
- The first argument is a pointer to a pthread_key_t variable.
- The second argument to pthread_key_t is a cleanup function.
- After you've created a key, each thread can set its thread-specific value corresponding to that key by calling pthread_setspecific.
- To retrieve a thread-specific data item, call pthread_getspecific, passing the key as its argument. http://siber.cankaya.edu.tr/SystemsProgramming/cfiles/tsd.ctsd.c (see Fig. 7)
Figure 7:
Per-Thread Log Files Implemented with Thread-Specific Data
|
- Observe that thread_function does not need to close the log file. close_thread_log was specified as the cleanup function for that key. Whenever a thread exits, that function is called to pass the thread-specific value for the thread log key.
2006-03-24