How do mutexes really work?

后端 未结 4 1698
深忆病人
深忆病人 2020-12-24 06:43

The idea behind mutexes is to only allow one thread access to a section of memory at any one time. If one thread locks the mutex, any other lock attempts will block until th

4条回答
  •  無奈伤痛
    2020-12-24 07:22

    A simple implementation that has been used in the past is to use a CPU level atomic "lock and exchange" instruction. This is a special instruction that atomically swaps a given value with a value in some memory location.

    A thread could acquire such a mutex by trying to swap a 1 value into the memory location. If the value comes back as 0, then the thread would assume that it has the mutex and would continue. Otherwise, if the value returned is 1, then the thread would know that some other thread currently has the mutex. In that case it would wait until trying again.

    The above is a highly simplified outline of what might happen in a simple system. Real operating systems are much more complex these days.

提交回复
热议问题