Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing different data members belonging to the same object from 2 different thread in C++

I have a few objects I need to perform actions on from different threads in c++. I known it is necessary to lock any variable that may be used by more than one thread at the same time, but what if each thread is accessing (writing to) a different data member of the same object? For example, each thread is calling a different method of the object and none of the methods called modify the same data member. Is it safe as long as I don't access the same data member or do I need to lock the whole object anyway?

I've looked around for explanations and details on this topic but every example seems to focus on single variables or non-member functions.

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

like image 938
user1357601 Avatar asked Apr 26 '12 13:04

user1357601


People also ask

Can two threads access same object?

No. They all use the same object. However, the memory system design of a typical modern computer means that some of the state of an object may be held in machine registers and memory caches associated with more than one processor in a multi-processor system.

What will happen if multiple threads accessing the same resource?

Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.

How can you share data between multiple threads?

All static and controlled data is shared between threads. All other data can also be shared through arguments/parameters and through based references, as long as the data is allocated and is not freed until all of the threads have finished using the data.

Can multiple threads read the same data?

This means two threads can read the same value and get different results creating a race condition. This can be prevented though memory barriers, correct use of volatile or a few other mechanisms.


2 Answers

It is effectively safe, but will strongly reduce the performance of your code if you do that often. Computers use things called "cache lines" and if two processors are working on the same cache line they'll have to pass it back & forth all the time, slowing your work down.

like image 198
dascandy Avatar answered Oct 20 '22 09:10

dascandy


Yes, it is safe to access different members of one object by different thread.

like image 37
Paskas Avatar answered Oct 20 '22 09:10

Paskas