在线程 A 中创建对象,在线程 B 中使用。需要互斥吗?

Create object in thread A, use in thread B. Mutex required?

我一直在阅读有关多线程、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

如果你也能向我推荐文章/书籍,我会很高兴,我可以在其中阅读更多关于这个主题的文章/书籍and/or搜索这些场景的正确关键字。

这很好,您不需要 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