2020-04-24 22:09:05 +00:00
|
|
|
package moreatomic
|
|
|
|
|
2020-05-06 07:32:21 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"golang.org/x/sync/semaphore"
|
|
|
|
)
|
2020-04-24 22:09:05 +00:00
|
|
|
|
|
|
|
type BusyMutex struct {
|
2020-05-06 07:32:21 +00:00
|
|
|
sema semaphore.Weighted
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
|
|
|
|
2020-05-06 07:32:21 +00:00
|
|
|
func NewBusyMutex() *BusyMutex {
|
|
|
|
return &BusyMutex{
|
|
|
|
sema: *semaphore.NewWeighted(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:32:21 +00:00
|
|
|
func (m *BusyMutex) TryLock() bool {
|
|
|
|
return m.sema.TryAcquire(1)
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *BusyMutex) IsBusy() bool {
|
2020-05-06 07:32:21 +00:00
|
|
|
if !m.sema.TryAcquire(1) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
m.sema.Release(1)
|
|
|
|
return true
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
|
|
|
|
2020-05-06 07:32:21 +00:00
|
|
|
func (m *BusyMutex) Lock(ctx context.Context) error {
|
|
|
|
return m.sema.Acquire(ctx, 1)
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *BusyMutex) Unlock() {
|
2020-05-06 07:32:21 +00:00
|
|
|
m.sema.Release(1)
|
2020-04-24 22:09:05 +00:00
|
|
|
}
|