If we have an object with two data members A, and B; Do we need any form of synchronization while accessing the two members from two different threads running in parallel? How about if the object was a global variable, versus the object was a heap object, accessed with a pointer to its address?
Edit: Each thread reads and writes into only one distinct member, a one-to-one association, the number of threads is equal to the number of data members, and threads access them distinctly, until they finish and join the main thread.
CodePudding user response:
The keywords you are looking for is memory model.
Non-bitfield members are distinct memory locations; there is no race condition from reading/writing different members.
A write in one thread and access in another of the same memory location is a potential conflict. Unless certain requirements are upheld (like happens before) this is a race condition, and your program has UB (undefined behaviour).
But access (read or write) to distinct members that are not bitfields won't trigger this.
The actual rules are more complex; not all bitfields share a memory location, for example.
CodePudding user response:
For a data-member that is accessed by only one thread, no synchronization is necessary. For a data-member that might be written to by a thread, and also might be accessed (in any way) by any other thread, synchronization is necessary.
It doesn't make a difference whether the object is global or on the heap, except that objects on the heap might be deleted while other threads still hold a pointer to them -- e.g. if thread 1 deletes the object while thread 2 is (potentially) accessing one or more data-members in that object, you've got a problem, because thread 2 may try to read or write to the now-free-memory locations where the data member used to be located, invoking undefined behavior. (You would typically avoid that problem by allocating the heap-object before creating the thread that will use it, and not deleting that heap-object until after that thread has exited and you've called join()
on it to be sure it's gone)
CodePudding user response:
1.If you only read A and B from different threads, there is no synchronization
2.If some threads read AB and some threads write them, there should be synchronizing, here you can use two read/write locks to avoid affecing each other while access A or B. you can use std::shared_mutex
to implement read/write lock