Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is boost::interprocess threadsafe?

Currently, I have 2 processes that communicate using the message_queue and shared_memory form boost. Everything work as attended.

Now I need to make one of this process multi threaded (thanks to boost again), and I was wondering if I need to use protection mechanism between the threads (such as mutex), or if the boost::interprocess library already provides a protection mechanism ?

I did not find any info on that on the boost documentation. By the way I'm using boost 1.40.

Thanks in advance.

like image 241
Tom97531 Avatar asked Oct 09 '22 16:10

Tom97531


1 Answers

The shared resources from boost::interprocess (shared memory, etc) require that you provide the necessary synchronization. The reason for this is that you may not require synchronization, and it usually a somewhat expensive operation performance wise.

Say for example that you had a process that wrote to shared memory the current statistics of something in 32-bit integer format, and a few processes that read those values. Since the values are integers (and therefore on your platform the reads and writes are atomic) and you have a single process writing them and a few process reading them, no synchronization is needed for this design.

However in some examples you will require synchronization, like if the above example had multiple writers, or if instead of integers you were using string data. There are various synchronization mechanisms inside of boost (as well as non-boost ones, but since your already using boost), described here:

[Boost info for stable version: 1.48] http://www.boost.org/doc/libs/1_48_0/doc/html/interprocess/synchronization_mechanisms.html

[Boost info for version your using: 1.40] http://www.boost.org/doc/libs/1_40_0/doc/html/interprocess/synchronization_mechanisms.html

With shared memory it is a common practice to place the synchronization mechanism at the base of the shared memory segment, where it can be anonymous (meaning the OS kernel does not provide access to it by name). This way all the processes know how to lock the shared memory segment, and you can associate locks with their segments (if you had multiple for example)

Remember that a mutex requires the same thread of execution (inside a process) to unlock it that locked it. If you require locking and unlocking a synchronization object from different threads of execution, you need a semaphore.

Please be sure that if you choose to use a mutex that it is an interprocess mutex (http://www.boost.org/doc/libs/1_48_0/doc/html/boost/interprocess/interprocess_mutex.html) as opposed to the mutex in the boost thread library which is for a single process with multiple threads.

like image 125
user1215153 Avatar answered Oct 12 '22 12:10

user1215153