Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::lock_guard seems to give thread safety despite scoped block

mutex m;
void thread_function()
{
    static int i = 0;

    for(int j =0; j<1000; j++)
    {
        { //this scope should make this ineffective according to my understanding
        lock_guard<mutex> lock(m);
        }
        i++;

       cout<<i<<endl;
    }
}

I call this function from 2 threads. Hence the expected value of int i is 1000*2 = 2000 if the function behaves in thread-safe fashion.

Without the mutex, the result varies from 1990 to 2000 as expected when printing i (due to non atomic int i). Inserting the lock guard without the scoped block prevents this.

However, by my understanding, having the scoped block around it should make it acquire and release the lock immediatly, hence there is no longer thread safety when writing to int i. However, I notice i to be 2000 always. Am I misunderstanding something?

like image 544
Sridhar Thiagarajan Avatar asked Nov 02 '25 09:11

Sridhar Thiagarajan


1 Answers

Your understanding is correct and that the result is always 2000 is probably machine-dependent. The reason could be that the synchronization just before the i++ statement on your machine happens to always cause the threads to execute it with sufficient distance in time to avoid the race condition. However, as said, this is not guaranteed.

like image 147
nielsen Avatar answered Nov 03 '25 23:11

nielsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!