Skip to content

Instantly share code, notes, and snippets.

@kwannoel
Created May 1, 2022 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwannoel/d51d5b871680c788c5ae4faf73a57641 to your computer and use it in GitHub Desktop.
Save kwannoel/d51d5b871680c788c5ae4faf73a57641 to your computer and use it in GitHub Desktop.
Mutex using channels and goroutines
import (
"fmt"
"sync"
)
type Mutex struct {
lockCh chan struct {}
unlockCh chan struct {}
doneCh chan struct {}
}
func createMutex() Mutex {
lockCh := make(chan struct {})
unlockCh := make(chan struct {})
doneCh := make(chan struct {})
// Spawn a goroutine which manages the lock
go func() {
for {
select {
case doneCh <- struct{} {}:
return
// only one can lock at a time
case <-lockCh: // permit lock
<-unlockCh // ensure exclusion until it is unlocked,
}
}
}()
return (Mutex {
lockCh,
unlockCh,
doneCh,
})
}
func (mutex Mutex) lock() {
mutex.lockCh<- struct {} {}
}
func (mutex Mutex) unlock() {
mutex.unlockCh<- struct {} {}
}
func (mutex Mutex) done() {
<-mutex.doneCh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment