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

十年热恋 提交于 2019-12-04 00:14:41

问题


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.


回答1:


This is fine, you don't need a mutex.

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]

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

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

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]

The completion of the thread represented by *this synchronizes with (1.10) the corresponding successful join() return.

For further reading:

  • 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


来源:https://stackoverflow.com/questions/46032965/create-object-in-thread-a-use-in-thread-b-mutex-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!