14

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.

user823255
  • 980
  • 9
  • 19
  • 3
    if only one thread is using the object,*and you can count on that*, then you should have no problem. – Basya Sep 04 '17 at 08:27

1 Answers1

17

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
LWimsey
  • 6,189
  • 2
  • 25
  • 53
  • 1
    Perfect, thank you very much. I was actually reading C++ concurrency in action but could not find these information. But I guess that is because I did not make the connection between thread creation and memory barrier in my head – user823255 Sep 04 '17 at 09:37
  • 1
    welcome.. It's sometimes challenging to find the common denominator since these are different topics usually covered in different chapters – LWimsey Sep 04 '17 at 09:42