TimedWait() for condition variable in sync package ?

900 views
Skip to first unread message

nicolas riesch

unread,
Nov 23, 2014, 6:47:52 PM11/23/14
to golan...@googlegroups.com
There is no TimedWait(timeout) function that returns after a timeout has elapsed, when waiting on a condition variable.

Is there a reason, or another way to achieve the same result ?


Steven Wiley

unread,
Nov 23, 2014, 8:13:00 PM11/23/14
to golan...@googlegroups.com
There is a function called AfterFunc in the time package.

func AfterFunc(d Duration, f func()) *Timer

AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method. http://golang.org/pkg/time/#Timer

There is also time.Sleep(d Duration) which just blocks for the specified time period. 

It sounds like you are polling, which is usually best avoided. It would be better if possible to block on a channel, and when the condition changes, send a message through the channel to release the block.

Ian Lance Taylor

unread,
Nov 23, 2014, 8:44:40 PM11/23/14
to nicolas riesch, golang-nuts
First I'll note that it's unusual to use condition variables in Go.
Mutexes are often useful. Condition variables rarely are. Code that
uses condition variables can usually be rewritten more comprehensibly
to use channels.

Timeouts in particular should be done using channels. If you need to
wait for some event with a timeout, convert that event into a channel
send, and use a select statement on that channel and
time.After(timeout).

Ian
Reply all
Reply to author
Forward
0 new messages