Just out of curiosity, what is the preferred way to achieve interprocess synchronization on Linux? The sem*(2)
family of system calls seem to have a very clunky and dated interface, while there are three ways to lock files - fcntl()
, flock()
and lockf()
.
What are the internal differences (if any) and how would you justify the usage of each?
You are suffering a wealth of choices from a rich history, as DarkDust noted. For what it's worth my decision tree goes something like this:
Use mutexes when only one process/thread can have access at a time.
Use semaphores when two or more (but nevertheless finite) processes/threads can use a resource.
Use POSIX semaphores unless you really need something SYSV semaphores have - e.g. UNDO, PID of last operation, etc.
Use file locking on files or if the above don't fit your requirements in some way.
Neither. The actual versions of pthread_*
(eg. phtread_mutex_t
) all allow to place the variables in shared segments that are created via shm_open
. You just have to place some extra parameter to the init calls.
Don't use semaphores (sem_t
) if you don't have to, they are too low level and are interupted by IO etc.
Don't abuse file locking for interprocess control. It is not made for that. In particular, you don't have a possibility to flush file meta-data such as locks, so you never know when a lock / unlock will become visible to a second process.
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