Go: proposal: sync: provide Cond.TimedWait(d time.Duration)

Created on 21 Dec 2017  路  5Comments  路  Source: golang/go

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

1.9

I would like to have the Condition variable to have a TimedWait method just like pthread_cond_timedwait so that the goroutine can suspend only for a given period of time.

I noticed that in the docs https://golang.org/pkg/sync/#Cond mention something Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal

Is this intentional?

I ask because I try to implement a blocking Queue and I'm using Cond to notify when the queue has an empty Slot to put items or when it has new items to read. It makes sense sometimes to wait for some time instead of until a signal arrives as I want to handle things gracefully. Currently, I'm trying to use a big for-select-case loop but it gets really messy.

I understand that its a very specific case. For me, it's nice to have that, but for some others, it might be not.

Thoughts?

FrozenDueToAge Proposal

Most helpful comment

Related: #16620 ("sync: mechanism to select on condition variables")

All 5 comments

Condition variables are rarely used in Go, because channels are more flexible. I don't think there is much interest in expanding the API used for condition variables. I don't know exactly what you are trying to do, but I suggest that you consider whether you can do it entirely with channels, rather than using a condition variable at all.

In particular, it's very easy to do a blocking FIFO queue of a certain size by using a channel of that size. Then a timed wait, for either adding to the queue or fetching an element from the queue, is simply a select on the queue channel and a time.After channel.

Related: #16620 ("sync: mechanism to select on condition variables")

@ianlancetaylor True.

The only real benefit of Conditions right now is the Broadcast call to notify all waiting clients that they need to check their predicate instead of having to wake up a random one and the put it back to sleep and then try waking up the one waiting for the correct condition that just became true.

The rationale is to give clients consuming the queue more control over their condition/predicate/assertion that they use while they wait for a signal.

The Related: #16620 select on condition variables looks like a good option I think.

/cc @dvyukov

We don't want to increase the API surface of condition variables.

Was this page helpful?
0 / 5 - 0 ratings