diff options
Diffstat (limited to 'utilities')
| -rw-r--r-- | utilities/utilities.go | 20 | ||||
| -rw-r--r-- | utilities/utilities_test.go | 30 |
2 files changed, 50 insertions, 0 deletions
diff --git a/utilities/utilities.go b/utilities/utilities.go index 377be56..e75d373 100644 --- a/utilities/utilities.go +++ b/utilities/utilities.go @@ -15,6 +15,7 @@ package utilities import ( + "context" "fmt" "math" "math/rand" @@ -22,6 +23,7 @@ import ( "reflect" "sort" "strings" + "sync" "sync/atomic" "time" @@ -209,3 +211,21 @@ func ApproximatelyEqual[T float32 | float64](truth T, maybe T, fudge T) bool { func UserAgent() string { return fmt.Sprintf("goresponsiveness/%s", GitVersion) } + +func WaitWithContext(ctxt context.Context, condition *func() bool, mu *sync.Mutex, c *sync.Cond) bool { + mu.Lock() + for !(*condition)() && ctxt.Err() == nil { + c.Wait() + } + return ctxt.Err() == nil +} + +func ContextSignaler(ctxt context.Context, st time.Duration, condition *func() bool, c *sync.Cond) { + for !(*condition)() && ctxt.Err() == nil { + time.Sleep(st) + } + if ctxt.Err() != nil { + c.Broadcast() + return + } +} diff --git a/utilities/utilities_test.go b/utilities/utilities_test.go index 3a84d76..aa66f6b 100644 --- a/utilities/utilities_test.go +++ b/utilities/utilities_test.go @@ -14,6 +14,7 @@ package utilities import ( + "context" "log" "sync" "testing" @@ -86,3 +87,32 @@ func TestFilenameAppend(t *testing.T) { t.Fatalf("%s != %s for FilenameAppend.", expected, result) } } + +func TestWaitWithContext(t *testing.T) { + ctxt, canceller := context.WithCancel(context.Background()) + never_true := func() bool { return false } + mu := sync.Mutex{} + cond := sync.NewCond(&mu) + + wg := sync.WaitGroup{} + + wg.Add(3) + + go func() { + ContextSignaler(ctxt, 500*time.Millisecond, &never_true, cond) + wg.Done() + }() + + go func() { + WaitWithContext(ctxt, &never_true, &mu, cond) + wg.Done() + }() + + go func() { + time.Sleep(2 * time.Second) + canceller() + wg.Done() + }() + + wg.Wait() +} |
