github.com/tursom/GoCollections@v0.3.10/concurrent/Cond.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package concurrent 8 9 import ( 10 "sync" 11 12 "github.com/tursom/GoCollections/util/time" 13 ) 14 15 type ( 16 Cond interface { 17 Signal() 18 Broadcast() 19 // Wait wait within unlocked environment 20 Wait() 21 // LockedWait wait within locked environment 22 LockedWait() 23 WaitOrTimeout(timeout time.Duration) bool 24 } 25 26 CondImpl sync.Cond 27 ) 28 29 func NewCond(l sync.Locker) Cond { 30 return (*CondImpl)(sync.NewCond(l)) 31 } 32 33 func (c *CondImpl) Signal() { 34 (*sync.Cond)(c).Signal() 35 } 36 37 func (c *CondImpl) Broadcast() { 38 (*sync.Cond)(c).Broadcast() 39 } 40 41 func (c *CondImpl) Wait() { 42 c.L.Lock() 43 defer c.L.Unlock() 44 (*sync.Cond)(c).Wait() 45 } 46 47 func (c *CondImpl) LockedWait() { 48 (*sync.Cond)(c).Wait() 49 } 50 51 func (c *CondImpl) WaitOrTimeout(timeout time.Duration) bool { 52 done := make(chan struct{}) 53 go func() { 54 c.L.Lock() 55 defer c.L.Unlock() 56 57 c.Wait() 58 close(done) 59 }() 60 61 select { 62 case <-time.After(timeout): 63 return false 64 case <-done: 65 return true 66 } 67 }