Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does accessing two different members of the same object need synchronization?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading