Make ctxCond nicer

This commit is contained in:
Łukasz Magiera 2020-06-05 20:04:59 +02:00
parent 958f74340b
commit f92ef92193
2 changed files with 15 additions and 18 deletions

View File

@ -10,8 +10,7 @@ import (
) )
type sectorLock struct { type sectorLock struct {
lk sync.Mutex cond *ctxCond
notif *ctxCond
r [FileTypes]uint r [FileTypes]uint
w SectorFileType w SectorFileType
@ -47,23 +46,21 @@ func (l *sectorLock) tryLock(read SectorFileType, write SectorFileType) bool {
} }
func (l *sectorLock) lock(ctx context.Context, read SectorFileType, write SectorFileType) error { func (l *sectorLock) lock(ctx context.Context, read SectorFileType, write SectorFileType) error {
l.lk.Lock() l.cond.L.Lock()
defer l.lk.Unlock() defer l.cond.L.Unlock()
for { for !l.tryLock(read, write) {
if l.tryLock(read, write) { if err := l.cond.Wait(ctx); err != nil {
return nil
}
if err := l.notif.Wait(ctx); err != nil {
return err return err
} }
} }
return nil
} }
func (l *sectorLock) unlock(read SectorFileType, write SectorFileType) { func (l *sectorLock) unlock(read SectorFileType, write SectorFileType) {
l.lk.Lock() l.cond.L.Lock()
defer l.lk.Unlock() defer l.cond.L.Unlock()
for i, set := range read.All() { for i, set := range read.All() {
if set { if set {
@ -73,7 +70,7 @@ func (l *sectorLock) unlock(read SectorFileType, write SectorFileType) {
l.w &= ^write l.w &= ^write
l.notif.Broadcast() l.cond.Broadcast()
} }
type indexLocks struct { type indexLocks struct {
@ -95,7 +92,7 @@ func (i *indexLocks) StorageLock(ctx context.Context, sector abi.SectorID, read
slk, ok := i.locks[sector] slk, ok := i.locks[sector]
if !ok { if !ok {
slk = &sectorLock{} slk = &sectorLock{}
slk.notif = newCtxCond(&slk.lk) slk.cond = newCtxCond(&sync.Mutex{})
i.locks[sector] = slk i.locks[sector] = slk
} }

View File

@ -8,14 +8,14 @@ import (
// like sync.Cond, but broadcast-only and with context handling // like sync.Cond, but broadcast-only and with context handling
type ctxCond struct { type ctxCond struct {
notif chan struct{} notif chan struct{}
l sync.Locker L sync.Locker
lk sync.Mutex lk sync.Mutex
} }
func newCtxCond(l sync.Locker) *ctxCond { func newCtxCond(l sync.Locker) *ctxCond {
return &ctxCond{ return &ctxCond{
l: l, L: l,
} }
} }
@ -37,8 +37,8 @@ func (c *ctxCond) Wait(ctx context.Context) error {
wait := c.notif wait := c.notif
c.lk.Unlock() c.lk.Unlock()
c.l.Unlock() c.L.Unlock()
defer c.l.Lock() defer c.L.Lock()
select { select {
case <-wait: case <-wait: