A mutex (short for mutual exclusion) is a synchronization object used to control access to a shared resource so that only one thread or process can access it at a time.
Key points:
- Purpose: Prevent race conditions where multiple threads or processes try to read/write the same resource simultaneously.
- Scope:
- In-process mutex: Synchronizes threads within the same application.
- Named/system-wide mutex: Can synchronize access across different processes.
- How it works:
- A thread/process requests the mutex.
- If it’s available, it acquires the lock and enters the critical section.
- If it’s already held, the thread waits until it’s released.
- After finishing, the thread releases the mutex so another can acquire it.
Analogy: Think of a mutex like a single bathroom key: only one person can enter at a time, and everyone else must wait until the key is returned.
// In-process
var mutex = new Mutex();
// Named mutex (cross-process)
var namedMutex = new Mutex(false, “Global\MyMutex”);
In this post, we will use named mutex or can be called cross-process mutex between two processes, process1 and process2 where both will read the counter from and write to the same file mycounter.txt. With mutex, it prevents Process1 and Process2 from overwriting each other at the same time by locking another process from access mycounter.txt till the lock, mutex here is released. In real world, multiple instance of web server might log to the same files so with mutex it will ensure they won’t overwrite each other’s logging.
Here is our process1 &2 console app with pipename mutex called “Global\VicMutexBtw2Processes” and do work 5 times reading and writing the field counter to and from mycounter.txt
Note: Global is keyword to tell the OS that it is a system-wide pipename that shared cross sessions whereas local is keyword to tell OS for within only current session.
P1

P2

Running P1 & P2 at the same time:
As expected with mutex, even though P1 & P2 both read and write to the same file mycounter.txt, they synchronize each other instead of overwritten one another
because with shared mutex pipedname “Global\\VicMutexBtw2Processes“, it allows one process to access the shared resource one at a time
with its mutex.WaitOne() to acquire the lock (mutex) and mutex.ReleaseMutex() to unlock it (to release mutex)

Sample of P1 and P2: https://tinyurl.com/bddpnrrz
