On 09/18/12 13:21, Stefan Teleman wrote:
On Tue, Sep 18, 2012 at 12:43 PM, Liviu Nicoara <[email protected]> wrote:

I am attaching a test program which, while 100% MT-safe, is flagged by
the Solaris thread analyzer.

The program as written is not thread safe. It is reading the value of
the counter variable and performing a zero comparison outside of a
mutex lock:

Stefan, I urge you to consider the argument on its merits. Yes, the thread 
analyzer flags it, but it is nonetheless MT-safe. Specifically:

1. writes are properly synchronized wrt themselves
2. reads are inherently thread-safe wrt themselves
3. reads are properly synchronized wrt writes
4.no thread can possibly observe an intermediate or otherwise incomplete value.

I will also add that the flag is either 0 or 1 during the execution of the 
program, with only one transition from 0 to 1, performed by one single thread.

I will concede that I might be wrong and I am open to arguments. I would accept 
as a counter-argument this program if you can show a runtime failure. I would 
also accept as argument a scenario under which two threads would see 
inconsistent/incorrect values or write the variable more than once, etc.

Thanks,
Liviu


for (size_t i = 0; i < nloops; ++i) {
         if (counter == 0) {  // <----------- !!!!
             pthread_mutex_lock (&lock);
             if (counter == 0)
                 ++counter;
             pthread_mutex_unlock (&lock);
         }
         else {
             // counter value is safe to use here
         }
     }

Reply via email to