[cpp-threads] Re: Thread API interface tweaks

Peter Dimov pdimov at mmltd.net
Wed Aug 30 21:20:28 BST 2006


Howard Hinnant wrote:

> PS:  In the interest of clarity, here's my entire recurisve_mutex,
> slightly modified from what I had before, after looking at
> Alexander's code (I believe checking count_ was harmless but
> unnecessary):
>
> template <class Mutex>
> class recursive_mutex
> {
> private:
>     Mutex& mut_;
>     unsigned count_;
>     thread_id id_;
> public:
>     explicit recursive_mutex(Mutex& mut)
>         : mut_(mut), count_(0) {}  // id_ has "not a thread" value
>
>     void lock()
>     {
>         thread_id self = thread_id::current();
>         if (id_ == self)

Here...

>             ++count_;
>         else
>         {
>             mut_.lock();
>             id_ = self;
>             store_release(&count_, 1);
>         }
>     }
>
>     void unlock()
>     {
>         if (--count_ == 0)
>         {
>             id_ = thread_id();  // id_ = "not a thread"

... and here... data race?

>             mut_.unlock();
>         }
>     }
> };

I have implemented a recursive mutex very similar to the above, but in my 
case the thread ID was an atomic type. The race is harmless when the type is 
atomic (right Alexander?) but the original spec has thread_id as an opaque 
non-atomic non-POD (right Howard? :-) ).

I agree that an atomic thread ID is useful.




More information about the cpp-threads mailing list