On Tue, Sep 18, 2012 at 4:35 PM, Liviu Nicoara <nikko...@hates.ms> wrote:
> 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. The the first read of the counter variable is outside a mutex lock correct? The read is followed by a 0 comparison, correct? What guarantees that between the read and the comparison the value of the counter variable hasn't been modified by another thread? The thread currently doing the comparison cannot guarantee it: it hasn't locked the mutex. Other threads may be running - actually they probably are. Another thread may have already acquired the mutex and incremented the value of counter. Your thread has no way of knowing if that has happened, because it does not yet have exclusive access to the counter variable. It will, after it acquires the mutex. Where is it reading the variable from? A register? Is it declared volatile? L2 cache? L3 cache? The program, as you wrote it, implicitly acknowledges that it is not thread safe. That is the point of the double check: one before the mutex lock, and one after it. The point of the first check has nothing to do with thread-safety, and everything to do with a minor optimization: if the value stored in variable counter is already not zero, then there's no point in locking the mutex or performing the increment. --Stefan -- Stefan Teleman KDE e.V. stefan.tele...@gmail.com