This is the first part of the Concurrency series. For your convenience you can find other parts using the links below:
Part 1 — Mutex performance in .NET
Part 2 — Java file lock
Part 3 — Java mutex via JNI
Part 4 — .NET with P/Invoke
Part 5 — WinAPI mutex
Part 6 — Abandoned mutex
Part 7 — Semaphores trickery
Part 8 — Tracking mutex owner
Part 9 — Semaphores with custom locks
Part 10 — Reentrant mutex
This is the first part of the Concurrency series in which I explore performance of various locking mechanisms. Once working on a pet project I started wondering how fast is a system wide lock in Windows so I decided to run few simple “benchmarks” just to get the general idea.
The benchmarks are deliberately done this way so I can compare different languages in the same manner. Do not take results for granted, do not consider them reliable.
First I explore WinAPI Mutex called from C#.
Code
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Diagnostics; using System.Threading; namespace MutexDotnet { class Program { static void Main(string[] args) { var mutex = new Mutex(false, "mutexName"); Stopwatch watch = new Stopwatch(); while (true) { watch.Restart(); for(int i = 0; i < 100000; ++i) { mutex.WaitOne(); mutex.ReleaseMutex(); } watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds); } } } } |
Nothing special, just a named mutex and stopwatch. I try to measure the time to acquire mutex 100 thousand times.
Results
Here are the results:
As we can see, to acquire mutex given number of times with 10 processes trying to do that concurrently we need over 4 seconds which gives 0.04 ms for single acquire + release.
In next parts we will see different mechanisms, their performance and quirks.