Implement mutex using channels

Concurrency primitives can be implemented on top of channel abstraction of CSP style. Here is an example of implementing mutex using channels.

Go code to implement mutex using channels.

package main

import "fmt"

type Lock struct {
	locked chan bool
}

func NewLock() Lock {
	lock := Lock{locked: make(chan bool, 1)}
	lock.locked <- true
	return lock
}

func (l *Lock) Lock() {
	<-l.locked // read from channel and if another read happens it waits
}

func (l *Lock) Unlock() {
	// This is not reentrant

	// calling unlock again on an unlocked channel blocks
	l.locked <- true // write to channel so, that it gets read and channel clears
}

This is not reentrant

[Read More]