在线程A中创建对象,在线程B中使用.是否需要互斥体? [英] Create object in thread A, use in thread B. Mutex required?

查看:144
本文介绍了在线程A中创建对象,在线程B中使用.是否需要互斥体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关多线程,C ++,适当的同步和锁定的各种内容,以防止出现竞争情况.但是,有一个问题没有为我回答: 如果我在线程A中创建了一个对象,但是之后却在线程B中专门使用了它,是否需要互斥锁?

I have been reading different things on multithreading, C++, proper synchronization and locks to prevent race conditions. One question has not been answered for me, however: Is there a mutex required if I create an object in thread A, but use it exclusively in thread B afterwards?

换句话说,我知道我不需要互斥体来防止出现竞争状况-我是否需要互斥体来充当内存屏障(或其他潜在问题)?

In other words, I know that I don't need a mutex to prevent race conditions - do I need a mutex to serve as a memory barrier (or other potential problems)?

一个非常基本的例子,可以直观地理解我的意思

A very basic example to visualize what I mean

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

如果您也可以向我推荐可以在该主题上阅读更多的文章/书和/或搜索这类情况的正确关键字,我将非常高兴.

I would be happy if you could also recommend me articles / books where I can read more into this topic and/or the right keywords to search for these kinds of scenarios.

推荐答案

这很好,您不需要mutex.

创建线程会设置内存屏障,因此可以安全地通过传递给worker_thread的引用来访问o.

Creating a thread sets a memory barrier, so it is safe to access o via the reference you passed to worker_thread.

§30.3.2.2-6-[thread.thread.constr]

§ 30.3.2.2-6 - [thread.thread.constr]

构造函数的调用完成与f副本的调用开始同步.

The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

worker_thread在运行时,显然,您可能无法在创建它的线程中访问o(如您所说).

While worker_thread is running, obviously you may not access o in the thread that created it (as you said).

加入线程也会设置障碍,因此在加入worker_thread之后,您可以在主线程中再次访问o.

Joining a thread sets a barrier too, so after worker_thread has joined, you can access o again in your main thread.

§30.3.2.5-4-[thread.thread.destr]

§ 30.3.2.5-4 - [thread.thread.destr]

由* this表示的线程的完成与(1.10)相应的成功join()返回同步.

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
  • Anthony Williams wrote a good book on parallel programming (C++ concurrency in action)
  • Bjarne Stroustrup's book (the C++ programming language, 4th edition) has two nice chapters on concurrent programming.
  • Jeff Preshing has a nice blog about many of these topics; check out preshing.com

这篇关于在线程A中创建对象,在线程B中使用.是否需要互斥体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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