Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions goose_std.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package std
import (
"math"
"sync"
"time"

"github.com/goose-lang/primitive"
"github.com/goose-lang/std/std_core"
Expand Down Expand Up @@ -164,3 +165,27 @@ func Multipar(num uint64, op func(uint64)) {
// is a simple way to do so - the model always requires one step to reduce this
// application to a value.
func Skip() {}

// WaitTimeout is like cond.Wait(), but waits for a maximum time of timeoutMs
// milliseconds.
//
// Not provided by sync.Cond, so we have to (inefficiently) implement this
// ourselves.
func WaitTimeout(cond *sync.Cond, timeoutMs uint64) {
done := make(chan struct{})
go func() {
cond.Wait()
cond.L.Unlock()
close(done)
}()
select {
case <-time.After(time.Duration(timeoutMs) * time.Millisecond):
// timed out
cond.L.Lock()
return
case <-done:
// Wait returned
cond.L.Lock()
return
}
}
10 changes: 10 additions & 0 deletions goose_std_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package std

import (
"math"
"sync"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -87,3 +88,12 @@ func TestSkip(t *testing.T) {
// nothing much to test, it does nothing
Skip()
}

func TestWaitTimeout(t *testing.T) {
var m sync.Mutex
c := sync.NewCond(&m)

m.Lock()
WaitTimeout(c, 10)
m.Unlock()
}