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) TryLock() bool {
|
|
|
|
// select {
|
|
|
|
// case m.mut <- struct{}{}:
|
|
|
|
// return true
|
|
|
|
// default:
|
|
|
|
// return false
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
|
|
|
|
// func (m *CtxMutex) IsBusy() bool {
|
|
|
|
// select {
|
|
|
|
// case m.mut <- struct{}{}:
|
|
|
|
// <-m.mut
|
|
|
|
// return false
|
|
|
|
// default:
|
|
|
|
// return true
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
|
|
|
|
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-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
|
|
|
}
|