1

I understood that I use mutexes but I don't understood how it works. I mean how it works inside.
How does it exclude another threads or processes when it locked, how does it know who is current owner and etc? Can a someone post a link on good article about it? Just I found only how it works from programmer's viewpoint, not its realization.

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123

2 Answers2

2

Implementation is platform and language specific.

Wikipedia lists several popular mutex algorithms and hardware solutions. https://en.wikipedia.org/wiki/Mutual_exclusion

Linux goes with futex https://en.wikipedia.org/wiki/Futex

Also check previous discussion

How are mutexes implemented?

Community
  • 1
  • 1
Serge
  • 3,387
  • 3
  • 16
  • 34
2

Depending on the platform/language it is implemented differently. I find Go's implementation nice to follow (not easy to follow, but more or less clear)

There, a mutex is a struct with two fields, 32 bit integers:

type Mutex struct {
    state int32
    sema  uint32
}

If the mutex is not already locked, then the operation basically amounts to a compare and swap instruction:

    // Fast path: grab unlocked mutex.
    if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
        if race.Enabled {
            race.Acquire(unsafe.Pointer(m))
        }
        return
    }

Compare and swap, from wikipedia, is:

In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a new given value.

The function signature looks like this:

func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

(How does this work, you ask? How does Compare and Swap work?)

If the mutex is not unlocked, then the Lock() method will have to wait (block the thread) until it can successfully swap the values at the Mutex's state.

One thing to keep in mind, is that a specific and immutable address in memory is essential for keeping a Mutex working, that is, you can't copy a mutex's value and pass it around -- it's/its a pointer to a shared space in memory.


There are resources out there for building a lock itself (although I find golangs more or less short implementation good enough)

http://pages.cs.wisc.edu/~remzi/OSTEP/threads-locks.pdf

https://www.andrew.cmu.edu/course/15-440-s12/applications/ln/lecture6.html

Community
  • 1
  • 1
Nevermore
  • 7,141
  • 5
  • 42
  • 64