vendredi 30 août 2019

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;
    }
}

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?

Aucun commentaire:

Enregistrer un commentaire