c++ - Locking when accessing shared memory for reading -
if accessing shared memory reading only, check condition if()
block, should still lock mutex? e.g.
mutex_lock(); if (var /* shared memory */) { } mutex_unlock();
is locking here needed , practice?
if variable reading written concurrently, yes, should acquire lock on mutex.
you read atomically if compiler provides necessary primitives that; either atomic features come c11 , c++11 or other language extension provided compiler. move mutex acquisition conditional, if wait until after test acquire mutex else may change between time test , time acquire mutex:
if (example) { // "example" variable changed here thread. mutex_lock(); // condition might false! mutex_unlock(); }
therefore, suggest acquiring mutex before conditional, unless profiling has pinpointed mutex acquisition bottleneck. (and in case tested variable larger cpu register -- 64-bit number on 32-bit cpu, example -- don't have option of delaying mutex acquisition without other kind of atomic fetch or compare primitive.)
Comments
Post a Comment