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

不想你离开。 提交于 2019-12-01 03:04:11

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