简体   繁体   中英

Thread specific data confusion in the given example

Hi i am reading this link to understand thread specific data.

After reading this, I got a question,

  1. The given example creates 5 threads.

  2. Each thread runs thread_function, which has its own stack. And each of this function invokes, another function called write_to_thread_log

  3. Now, write_to_thread_log function also will be running on the context of each specific thread, in this case, why do we need thread specific data.

There are plenty of explanation i found in the net, but somehow my brain is not understanding. Please help me to understand.

If I undestand this question correctly, you just don't realize intention of thread-specific data.

Yes, you can implement this example without using pthread_key mechanism. Instead, you may pass file descriptor to function write_to_thread_log via parameter:

void write_to_thread_log (FILE* thread_log, const char* message)

But then you should pass this parameter to every function , which possibly call(even indirectly!) this one. Because logging usually cover almost whole program, you end up with adding additional parameter to every function in the program , which is not convenient.

Single-threaded program can use global variables for store values, which can be used in many places. Because all functions can use global variables, there is no needs to pass additional parameter to them.

But in case of multi-threaded program, threads share value of the global variable, so this approach doesn't suite to thread-specific data.

pthread_key mechanism resolve this problem: while every thread sees same value of the global key, data corresponded to this key is thread-specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM