从C ++中的2个不同线程访问属于同一对象的不同数据成员 [英] Accessing different data members belonging to the same object from 2 different thread in C++

查看:64
本文介绍了从C ++中的2个不同线程访问属于同一对象的不同数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些对象需要在c ++中的不同线程上执行操作.我知道有必要锁定可能同时被多个线程使用的任何变量,但是如果每个线程正在访问(写入)同一对象的不同数据成员怎么办?例如,每个线程都在调用对象的不同方法,而所调用的方法均未修改同一数据成员.只要我不访问相同的数据成员,它是否安全?还是我需要锁定整个对象?

我到处寻找有关此主题的解释和详细信息,但是每个示例似乎都集中在单个变量或非成员函数上.

总结一下:我可以安全地从2个不同的线程访问同一对象的2个不同的数据成员,而无需在整个对象上加锁吗?

解决方案

它实际上是安全的,但是如果您经常这样做,则会大大降低代码的性能.计算机使用称为高速缓存行"的东西,如果两个处理器在同一高速缓存行上工作,则必须将其传递回&一直在四处走动,这会减慢您的工作速度.

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?

解决方案

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.

这篇关于从C ++中的2个不同线程访问属于同一对象的不同数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆