Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 556
user823255 Avatar asked Sep 04 '17 08:09

user823255


1 Answers

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
like image 52
LWimsey Avatar answered Oct 04 '22 16:10

LWimsey