Question

My question is related with the work logic of mutexes in shared memory objects which are used by multiple applications.

Let's say we have two functions which are performing some operations on an object which is created in the shared memory.

void funcA ()
{
// put some mutex here

/*
.
do the operation on the shared object here
.
*/
}

void funcB ()
{
// put some mutex here

/*
.
do the operation on the shared object here
.
*/
}

So since the mutexes lock the code not the shared memory object, is it possible that one application calls funcA and do some operation on shared object and another application calls funcB to do another operation on the same object at the same time?

And how to prevent that behaviour? Which boost mutex type is suitable for multi-process and applications?

Was it helpful?

Solution

I don't know about boost implementations, but if you're on a platform with posix threads, you can do this using the native thread implementation. You create a pthread_mutex_t with a "process shared" attribute, and put it into shared memory where you can access it from both processes.

There's a section detailing how to do this in Daryl Gove's (excellent) book on Multicore Application Programming, which is well worth a read for multithreaded C++ development anyway. The mutex attribute part of his example is:

pthread_mutex_t * mutex;
pthread_mutexattr_t attributes;
pthread_mutexattr_init( &attributes );
pthread_mutexattr_setpshared( &attributes, PTHREAD_PROCESS_SHARED );
...

After then setting the attributes on the mutex, this defines the mutex as being a process shared mutex, which you can then put into shared memory to access it from multiple processes and protect access to your shared data structures.

Given that it exists in posix threading implementation, it's worth having a closer look for process shared attributes in the boost thread library to see if this is exposed for use there, too.

[ Edit: I've just noticed the visual studio tag on your post, so you're using Windows threads - apologies for the posix-focused answer!

Using Windows threads (again natively), you can share a mutex between process by creating a named mutex, and accessing it by name across multiple processes. ]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top