Created
May 1, 2022 08:02
-
-
Save kwannoel/d51d5b871680c788c5ae4faf73a57641 to your computer and use it in GitHub Desktop.
Mutex using channels and goroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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