Locking when accessing shared memory for reading

前端 未结 1 549
迷失自我
迷失自我 2021-01-06 09:36

If I am accessing shared memory for reading only, to check a condition for an if() block, should I still lock the mutex? E.g.

mutex_lock();

if          


        
相关标签:
1条回答
  • 2021-01-06 09:54

    If the variable you are reading could be written to concurrently, then yes, you should acquire a lock on the mutex.

    You could only read it atomically if your compiler provides you with the necessary primitives for that; this could be either the atomic features that come with C11 and C++11 or some other language extension provided by your compiler. Then you could move the mutex acquisition into the conditional, but if you wait until after the test to acquire the mutex then someone else may change it between the time you test it and the time you acquire the mutex:

    if (example) {
        // "example" variable could be changed here by another thread.
    
        mutex_lock();
    
        // Now the condition might be false!
    
        mutex_unlock();
    }
    

    Therefore, I would suggest acquiring the mutex before the conditional, unless profiling has pinpointed mutex acquisition as a bottleneck. (And in the case where the tested variable is larger than a CPU register -- a 64-bit number on a 32-bit CPU, for example -- then you don't even have the option of delaying mutex acquisition without some other kind of atomic fetch or compare primitive.)

    0 讨论(0)
提交回复
热议问题