What is a mutex ?
A mutex is a locking mechanism used to control concurrent access to a resource.
It allows only one task, process, thread, to access the resource at any given time.
Mutex working
A process must first attempt to lock the mutex before accessing the protected resource.
If the process fails to lock the mutex, it can:
1. wait on the mutex
wait for the mutex to be unlocked
a timeout period can be specified to prevent indefinite waits.
2. fail and proceed with execution.
Once the lock is obtained, the process is free to access the resource.
Once its done, it must release the lock on the mutex.
Mutex Analogy
A mutex is like a bathroom key. The bathroom is always locked and only the person with the key can use it.
The bathroom is the protected resource while the key is the mutex.
Mutexes for Linux shells
Linux shells do not have built-in mutexes.
However, it is possible to simulate them using the following approaches:
1. flock
flock
is a linux utility used to manage advisory locks on open files from within a shell script or the commandline.
It can be used to obtain shared or exclusive access to a file.
This ensures synchronized access to the file and also the file content is protected from accidental corruption.
The flock utility can also be used to release the file locks.
Any file locks not released, are automatically released when the process ends.
2. mkdir