C++11 堆栈变量的线程安全
我对 C++11 中的新线程有点困惑。我知道如何使用互斥体来阻止两个线程同时操作相同的数据,但是分配给该数据怎么样?
例子!
class Foo
{
std::string s;
// This would be called on a seperate thread
void Bar() { s = std::string( "blah blah blah" ); }
};
所以我要问的是,因为我给 s 赋值了一些东西,所以成员变量 s 是否总是保留在相同的内存位置,并且赋值只是更改内部数据,在这种情况下我只需要一个互斥锁?或者我仍然可以进入具有缓存值的情况以及意味着我需要开始使用atomic<>的情况吗?确保我拥有最新数据?或者这仅适用于整数或结构等类型?
I'm getting a bit confused with the new threading in C++11. I get how I can use mutexes to stop two threads from operating on the same data at the same time, but what about assigning to that data?
Example!
class Foo
{
std::string s;
// This would be called on a seperate thread
void Bar() { s = std::string( "blah blah blah" ); }
};
So what I'm asking is, because I'm assigning something to s, does the member variable s always stay in the same memory location, and assignments just change the internal data, in which case I just need a mutex? Or can I still get into situations with cached values and things which mean I need to start using atomic<> to make sure I have the up to date data? Or is that just for types like ints, or structs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
互斥体保证足够。无论需要什么魔法才能发挥作用,它们都包含在内。只要访问或修改
s
任何特定实例的每个线程都在相同互斥体的保护下进行操作,就不会有问题。访问和分配之间的唯一区别是 - 您不需要互斥锁来防止两个线程同时读取相同的数据。仅当一个对象可以在一个线程中修改,而另一个线程正在或可能正在访问该对象时,才需要互斥锁。允许并发读取。
请注意,这是通常的规则,适用于
std::string
等典型对象。如果愿意的话,可以创建一个在并发读取时甚至在一个线程中读取一个对象而在另一个线程中读取相同类型的不同对象时也能保持平衡的对象。 (但这样的东西没有用,人们不应该制造它们。)Mutexes are guaranteed sufficient. Whatever magic is needed to make it work, they contain. So long as every thread that accesses or modifies any particular instance of
s
does so under protection of the same mutex, there will be no issue.The only difference between access and assignment is this -- you do not need a mutex to prevent two threads from reading the same data at the same time. A mutex is only required when an object may be modified in one thread while another thread is or might be accessing it. Concurrent reads are permitted.
Note that this is the usual rule and applies to typical objects like
std::string
. One can, if one wishes to, make an object that breaks even with concurrent reads and even when one object is read in one thread while a different object of the same type is read in another thread. (But such objects are not useful and people just shouldn't make them.)