Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? :)

like image 277
John Humphreys Avatar asked Jan 24 '12 14:01

John Humphreys


2 Answers

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.

like image 131
Mike Seymour Avatar answered Oct 03 '22 19:10

Mike Seymour


  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.

like image 31
stefaanv Avatar answered Oct 03 '22 19:10

stefaanv