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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With