0

Wanted to see how a mutex looks in x86 assembler. Originally wrote a C++ app, using C++11:

#include <mutex>

int main(){
    std::mutex m;
    volatile int i = 0;

    m.lock();
    i = 6;
    m.unlock();

    return 0;
}

but when I checked the assembly output file there was 1000+ lines of asm and I couldn't see any atomic or LOCK instructions.

So moving on, I found this website showing how a mutex can be written in x86:

http://forum.codecall.net/topic/64301-writing-a-simple-lock-mutex-in-cassembly/

I have seen other x86 mutex implementations in white papers which seem far more complicated, (some used CMPXCHG), so I wondered if the below code contains any hidden race conditions or problems? The code seems too simple.

user3811839
  • 141
  • 7

1 Answers1

0

It is broken implementation since there is no any waiting if the mutex is locked already.

See this question for some simple implementations: The cost of atomic counters and spinlocks on x86(_64)

Community
  • 1
  • 1
Anton
  • 6,349
  • 1
  • 25
  • 53
  • So unless I am mistaken, it is missing a BNE after the XCHG in lock() and if they aren't equal, jump back to the beginning and re-do XCHG? (is this classed as "waiting", because it would keep on doing this over and over again until it succeeded?) – user3811839 Aug 20 '14 at 14:16
  • for minimal implementations - yes. Also, I see no point in the `value` variable and thus in two `mov` instuctions – Anton Aug 20 '14 at 14:19
  • Have you seen the link? I think value is used inside main()? – user3811839 Aug 20 '14 at 14:29
  • it's useless for real application because it is global and not protected by the mutex – Anton Aug 20 '14 at 14:53
  • Well the protection comes from the locking of the mutex before and after its usage (in the link), surely? – user3811839 Aug 20 '14 at 15:20
  • no, in `unlock`, the `mov` is after updating `lock_var` and thus is unprotected – Anton Aug 20 '14 at 15:26
  • Ok- I mean if you were to remove the two redundant lines you mentioned in your first comment.... – user3811839 Aug 20 '14 at 15:59