Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing non-thread-safe objects through thread-safe containers

I have a thread-safe object queue which is designed to model a pipeline of work moving between a chain of threads. In some cases, I want to pass non-thread-safe objects (e.g., std::vectors, or other STL containers) as part of these work items.

Now, in the case you have a shared object between threads, there is an obvious problem of load/store ordering in ensuring object consistency. Since the thread-safe queue ensures that only one thread has ownership of the object there is no chance for multiple threads trying to modify or read the object at the same time.. the only possible problem I see is ensuring memory consistency in previously issued loads/stores on the object by previous owner threads.

The queue ensures thread safety by creating a lock_guard<...> on queue operations. Wouldn't memory consistency of the object being moved between threads be guaranteed since the memory fencing and synchronization would be taken care by the lock_guard?

Part of me wants to ensure I am only passing thread-safe objects between threads, but I feel like this case there should be no problem. Is this true?

like image 987
0n1 Avatar asked Nov 22 '25 07:11

0n1


1 Answers

The queue ensures thread safety by creating a lock_guard<...> on queue operations. Wouldn't memory consistency of the object being moved between threads be guaranteed since the memory fencing and synchronization would be taken care by the lock_guard?

Yes.

Part of me wants to ensure I am only passing thread-safe objects between threads, but I feel like this case there should be no problem. Is this true?

Yes.

This is essentially why volatile is inapplicable as a device for concurrent data access in C++; it doesn't solve race conditions and, once you've brought concurrency devices (e.g. mutexes) into the fray to fix that, those are also taking care of the memory consistency issue so there's simply nothing left for volatile to do.

like image 66
Lightness Races in Orbit Avatar answered Nov 24 '25 22:11

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!