Ask HN: Can a mutex have a race condition?

3 points by hahnchen ↗ HN
If two threads lock a mutex at the same time, wont both of them think they both hold the lock?

But then, if there’s a way to lock a mutex so that it’s impossible for two threads to do it at the same time, why not use that mechanism to modify whatever shared variable is in question?

I imagine that pthread or <insert other threading library>’s provided mutex is, internally, an integer which is set to 1 or 0 depending on the mutex’s state.

if i want to share an integer from my program with another thread, why cant I just use whatever is used by the mutex?

5 comments

[ 5.8 ms ] story [ 38.2 ms ] thread
> If two threads lock a mutex at the same time, wont both of them think they both hold the lock?

If that is possible to happen, you don't have a correctly implemented mutex.

So no.

> But then, if there’s a way to lock a mutex so that it’s impossible for two threads to do it at the same time, why not use that mechanism to modify whatever shared variable is in question?

Because it's fiddly and hardware-dependent. Do you want to rewrite your concurrency code, just because you moved your program to a slightly different processor?

Also, adon't you need other data types than a bit (or a small integer)? The hardware-supported exclusion mechanism certainly won't know about strings or your ApplicationFactory class.

If you know that accesses to an integer are atomic (which they tend to be in C) then you don't need any thread synchronisation, though it's probably to be considered a bad practice.
You need more than just atomic access I think. You need an atomic compare and swap. These are usually a hardware affordance. To properly use them most languages provide an atomic int that expose the hardware version in an ergonomic interface. This is then typically wrapped in a Mutex library that exposes an even more ergonomic interface than the atomic primitive. You can sometimes rely just on the atomic primitive if that's all you need but most of the time you need more.
If all you need is atomic compare and swap of a word-sized integer; you can probably find that without a mutex.

If your structure is larger than your architecture can do atomic compare and swap, then you'll need something else.

Mutexes usually give you a mechanism to wait for held locks as well. Often without spinning, sometimes with some degree of fairness.