How do mutexes really work?

后端 未结 4 1704
深忆病人
深忆病人 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:44

    Here's a quick overview of what a mutex needs to work, it's a shortened form of my complete article How does a mutex work?

    • There is an integer in memory that represents the locked state, with a value 1 or 0.
    • The mutex needs an atomic compare_and_swap function that can atomically attempt to modify that value and report whether it succeeded. This allows a thread to both check and modify the state at the same time.
    • The OS needs to provide a function to wait in the case the mutex is locked. On Linux the low-level function is futex. This will place the thread in a queue, and also monitor the integer in memory.
    • The operations involved also include data fences, to prevent modifications in memory from being visible prior to the lock, and being completely available after the lock.

提交回复
热议问题