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? 🙂
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 thatpthread_thas a suitable ordering defined, and automatic cleanup along with all the other thread resources.You could use C++11’s
thread_localkeyword, orboost::thread_specific_ptr, if you don’t like the Posix API.