How are mutexes implemented?

后端 未结 6 1838
自闭症患者
自闭症患者 2020-11-30 20:35

Are some implementations better than others for specific applications? Is there anything to earn by rolling out your own?

6条回答
  •  遥遥无期
    2020-11-30 21:29

    A bit of assembly to demonstrate locking atomically:

    ; BL is the mutex id
    ; shared_val, a memory address
    
    CMP [shared_val],BL ; Perhaps it is locked to us anyway
    JZ .OutLoop2
    .Loop1:
    CMP [shared_val],0xFF ; Free
    JZ .OutLoop1 ; Yes
    pause ; equal to rep nop.
    JMP .Loop1 ; Else, retry
    
    .OutLoop1:
    
    ; Lock is free, grab it
    MOV AL,0xFF
    LOCK CMPXCHG [shared_val],BL
    JNZ .Loop1 ; Write failed
    
    .OutLoop2: ; Lock Acquired
    

提交回复
热议问题