2020-04-24 22:09:05 +00:00
|
|
|
package moreatomic
|
|
|
|
|
2020-05-06 07:32:21 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
2020-04-24 22:09:05 +00:00
|
|
|
|
2020-05-06 07:40:26 +00:00
|
|
|
type CtxMutex struct {
|
|
|
|
mut chan struct{}
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
|
|
|
|
2020-05-06 07:40:26 +00:00
|
|
|
func NewCtxMutex() *CtxMutex {
|
|
|
|
return &CtxMutex{
|
|
|
|
mut: make(chan struct{}, 1),
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
2020-05-06 07:32:21 +00:00
|
|
|
}
|
2020-04-24 22:09:05 +00:00
|
|
|
|
2020-05-06 07:40:26 +00:00
|
|
|
func (m *CtxMutex) Lock(ctx context.Context) error {
|
|
|
|
select {
|
|
|
|
case m.mut <- struct{}{}:
|
|
|
|
return nil
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
2020-05-06 07:32:21 +00:00
|
|
|
}
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
|
|
|
|
2020-08-04 21:09:37 +00:00
|
|
|
// TryUnlock returns true if the mutex has been unlocked.
|
|
|
|
func (m *CtxMutex) TryUnlock() bool {
|
|
|
|
select {
|
|
|
|
case <-m.mut:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-06 07:40:26 +00:00
|
|
|
func (m *CtxMutex) Unlock() {
|
|
|
|
select {
|
|
|
|
case <-m.mut:
|
|
|
|
// return
|
|
|
|
default:
|
|
|
|
panic("Unlock of already unlocked mutex.")
|
|
|
|
}
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|