Created
August 18, 2019 09:12
-
-
Save Tomotoes/cfa5b0ed759dc90f47ea5359ff75fae6 to your computer and use it in GitHub Desktop.
Mutex with channel
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
package main | |
import "time" | |
type Mutex struct { | |
lock chan struct{} | |
} | |
func New() *Mutex { | |
mu := &Mutex{lock: make(chan struct{}, 1)} | |
mu.lock <- struct{}{} | |
return mu | |
} | |
func (mu *Mutex) Lock() { | |
<-mu.lock | |
} | |
func (mu *Mutex) Unlock() { | |
select { | |
case mu.lock <- struct{}{}: | |
default: | |
panic("unlock of unlocked mutex") | |
} | |
} | |
func (mu *Mutex) TryLock() bool { | |
select { | |
case <-mu.lock: | |
return true | |
default: | |
} | |
return false | |
} | |
func (mu *Mutex) TryLockWithTimeout(timeout time.Duration) bool { | |
select { | |
case <-mu.lock: | |
return true | |
case <-time.After(timeout): | |
} | |
return false | |
} | |
func (mu *Mutex) IsLocked() bool { | |
return len(mu.lock) == 0 | |
} | |
func main() { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment