[cpp-threads] Re: Thread API interface tweaks

Howard Hinnant hinnant at twcny.rr.com
Wed Aug 30 23:14:16 BST 2006


I appreciate the free analysis. :-)  Here's my understanding:

On Aug 30, 2006, at 4:20 PM, Peter Dimov wrote:

>> 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...

If id_ != self, then obviously this branch isn't taken.  Also no  
other thread is capable of setting id_ to self.  Some other thread  
might change id_, but only from one value that is not self to another  
value that is not self.  If id_ == self, then no other thread is  
capable of changing the value of id_ at all.  And in this case, no  
other thread has the ability to change count_ at all.

>
>>             ++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?

It is undefined for a thread for which id_ != self to call unlock().   
Since id_ is known to be self, it is also known here that no other  
thread can change id_ to some other value.  Even after this thread  
sets id_ to "invalid" some other thread  attempting to change id_  
must first do mut_.lock(), which won't succeed until this thread  
executes mut_.unlock().

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

-Howard




More information about the cpp-threads mailing list