Access to different data elements belonging to the same object from 2 different streams in C ++

I have several objects needed to perform actions from different threads in C ++. I knew that it was necessary to block any variable that could be used by more than one thread at a time, but what if each thread accessed (written) to another data member of the same object? For example, each thread invokes a different method of the object, and not one of the methods called modification of the same data element. Is it safe until I get access to the same data item or do I need to lock the entire object?

I looked through the explanations and details on this topic, but each example seems to focus on single variables or non-member functions.

To summarize: Can I safely access 2 different data elements of the same object from 2 different threads without placing a lock on the whole object?

+5
source share
6 answers

This is effectively safe, but will significantly reduce the performance of your code if you do this often. Computers use things called "cache lines", and if two processors are running on the same cache line, they will have to go back and forth all the time, slowing down.

+4
source

Yes, it is safe to access different members of the same object using different threads.

+2
source

, . , , , ..

, . , , . .

+1

, ?

. , 100 , . , , , .

: " ?" , , .

0

Well, yes, well, you can do it, but as others have pointed out, you don’t have to. IMHO, access to data elements must be done using getter / setter methods so that any necessary mutexing / criticalSectioning / semaphoring / any are encapsulated inside the object.

0
source

You can be careful. See for example http://gcc.gnu.org/ml/gcc/2012-02/msg00032.html Depending on how the fields are available, you may encounter similar difficulties to find problems.

0
source

All Articles