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

回眸只為那壹抹淺笑 提交于 2021-02-07 07:09:05

问题


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?


回答1:


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.




回答2:


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




回答3:


I think you can do that fine. But you better be sure that that the method internals never change to access the same data or the calling program doesn't decide to call another method that another thread is already using etc.

So possible, but potentially dangerous. But then it will also be quicker because you'll be avoiding calls to get mutexes. Pick your poison.




回答4:


Is it safe as long as I don't access the same data member or do I need to lock the whole object anyway?

The answer totally depends upon the design of the class, However I would still say that it is always recommended to think 100 times before allowing multiple threads to access same object. Given the fact, If you are sure that the data is really independent their is NO need to lock the whole object.

Then a different question arises, "If variables are indeed independent Why they are in same class ?" Be careful threading kills if mistaken.




回答5:


Well, yes, OK you can do it but, as others have pointed out, you should not have to. IMHO, access to data members should be via getter/setter methods so that any necessary mutexing/criticalSectioning/semaphoring/whatever is encapsulated within the object.




回答6:


You might want to be careful. See for example http://gcc.gnu.org/ml/gcc/2012-02/msg00032.html Depending on how the fields are accessed, you might run across similar hard to find problems.



来源:https://stackoverflow.com/questions/10334879/accessing-different-data-members-belonging-to-the-same-object-from-2-different-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!