Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Locking vs. Semaphores

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?

like image 301
Blagovest Buyukliev Avatar asked Aug 25 '10 17:08

Blagovest Buyukliev


2 Answers

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.

like image 64
Duck Avatar answered Oct 05 '22 16:10

Duck


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.

like image 36
Jens Gustedt Avatar answered Oct 05 '22 14:10

Jens Gustedt