开发者

Why do we need boost::thread_specific_ptr?

开发者 https://www.devze.com 2023-03-18 20:34 出处:网络
Why do we need boost::thread_specific_ptr, or in other words what can we not easily do without it? I can see why pthread provides pthread_getspecific() etc. These functions are useful for cleaning u

Why do we need boost::thread_specific_ptr, or in other words what can we not easily do without it?

I can see why pthread provides pthread_getspecific() etc. These functions are useful for cleaning up after dead threads, and handy to call from C-style functions (the obvious alternative being to pass a pointer everywhere that points to some memory allocated before the thread was created).

In contrast, the constructor of boost:thread takes a callable class by value, and everything non-static in that class becomes thread local once it is开发者_如何学Python copied. I cannot see why I would want to use boost::thread_specific_ptr in preference to a class member any more than I would want to use a global variable in OOP code.

Do I horribly misunderstand anything? A very brief example would help, please. Many thanks.


thread_specific_ptr simply provides portable thread local data access. You don't have to be managing your threads with Boost.Thread to get value from this. The canonical example is the one cited in the Boost docs for this class:

One example is the C errno variable, used for storing the error code related to functions from the Standard C library. It is common practice (and required by POSIX) for compilers that support multi-threaded applications to provide a separate instance of errno for each thread, in order to avoid different threads competing to read or update the value.

0

精彩评论

暂无评论...
验证码 换一张
取 消