简体   繁体   中英

Thread-specific data - why can't I just use a static map with thread IDs?

While reading up on POSIX threading, I came across an example of thread-specific-data. I did have one area of confusion in my mind...

The thread-specific-data interface looks a little clunky, especially once you mix in having to use pthread_once, the various initializers, etc.

Is there any reason I can't just use a static std::map where the key is the pthread_self() id and the data value is held in the second part of the std::pair?

I can't think of a reason that this wouldn't work as long as it was wrapped in a mutex, but I see no suggestion of it or anything similar which confuses me given it sounds much easier than the provided API. I know threading can have alot of catch-22's so I thought I'd ask and see if I was about to step in... something unpleasant? :)

I can't think of a reason that this wouldn't work as long as it was wrapped in a mutex

That in itself is a very good reason; implemented properly, you can access your thread-specific data without preventing other threads from simultaneously creating or accessing theirs.

There's also general efficiency (constant time access, versus logarithmic time if you use std::map ), no guarantee that pthread_t has a suitable ordering defined, and automatic cleanup along with all the other thread resources.

You could use C++11's thread_local keyword, or boost::thread_specific_ptr , if you don't like the Posix API.

  1. pthread thread-specific-data existed before the standard library containers
  2. thread-specific-data avoids the need of locking and makes sure no other thread messes with the data
  3. The data is cleaned up automatically when the thread disappears

Having said that, nothing stops you from using your own solution. If you can be sure that the container is completely constructed before any threads are running (static threading model), you don't even need the mutex.

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