HACKER Q&A
📣 hahnchen

Can a mutex have a race condition?


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 ’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?


  👤 Tomte Accepted Answer ✓
> 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.


👤 toast0
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.


👤 mytailorisrich
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.