我一直在阅读有关多线程、C++、正确同步和防止竞争条件的锁的不同内容。但是,我没有回答一个问题: 如果我在线程 A 中创建了一个对象,但之后只在线程 B 中使用它,是否需要互斥锁?
换句话说,我知道我不需要互斥锁来防止竞争条件 - 我是否需要互斥锁来充当内存屏障(或其他潜在问题)?
一个非常基本的例子来形象化我的意思
struct Object {
void do_stuff();
};
Object o;
std::thread worker_thread([&o](){
while (alive)
o.do_stuff();
}).join();
// `o` is never used outside worker_thread
如果您还可以向我推荐一些文章/书籍,我会很高兴,我可以在这些文章/书籍中阅读更多有关此主题的内容和/或搜索此类场景的正确关键字。
最佳答案
这很好,您不需要 mutex
。
创建线程会设置内存屏障,因此通过您传递给 worker_thread
的引用访问 o
是安全的。
§ 30.3.2.2-6 - [thread.thread.constr]
The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.
虽然 worker_thread
正在运行,但显然您可能无法在创建它的线程中访问 o
(如您所说)。
加入线程也会设置障碍,所以在 worker_thread
加入后,您可以在主线程中再次访问 o
。
§ 30.3.2.5-4 - [thread.thread.destr]
The completion of the thread represented by *this synchronizes with (1.10) the corresponding successful join() return.
进一步阅读:
- Anthony Williams 写了一本关于并行编程的好书(C++ 并发)
- Bjarne Stroustrup 的书(C++ 编程语言,第 4 版)有两个关于并发编程的精彩章节。
- Jeff Preshing 有一篇关于这些主题的精彩博客;查看 preshing.com
关于c++ - 在线程 A 中创建对象,在线程 B 中使用。需要互斥锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032965/