Named semaphore or flock that is better than C linux

I am trying to create shared memory that will be used by several processes. these processes interact with each other using MPI calls ( MPI_Send , MPI_Recv ).

I need a mechanism to control access to this shared memory. Yesterday I added a question to find out if MPI supports any tool for this. A shared memory access control mechanism for processes created by MPI , but MPI does not seem to exist.

So I need to choose between named semaphore or flock .

For the named semaphore, if any of the processes suddenly dies without calling sem_cloe() , this semaphore always remains and ll /dev/shm/ can be noticed. This sometimes leads to a deadlock (if I run the same code again!), For this reason I am now thinking about using the pack.

Just wanted to confirm whether flock is suitable for this type of operation?

Are there any disadvantages to using flock ?

Is there anything else besides named semaphore and flock that can be used here?

I am working on C under linux.

+7
source share
1 answer

You can also use the POSIX mutex in shared memory; you just need to set the "pshared" attribute first. See pthread_mutexattr_setpshared . This is perhaps the most direct way to do what you want.

However, you can also call sem_unlink your semaphore while you are still using it. This will delete it from the file system, but the main semaphore object will continue to exist until the last process calls sem_close on it (which happens automatically if the process terminates or fails).

I can imagine two minor flaws in using flock . Firstly, it is not POSIX, so it makes your code somewhat less portable, although I believe that most Unixes put it into practice. Secondly, it is implemented as a system call, so it will be slower. Both pthread_mutex_lock and sem_wait use the "futex" mechanism on Linux, which only makes a system call when you really need to wait. This is just a problem if you grab a lot and release the lock.

+8
source

All Articles