Sync.wait()?

101 views
Skip to first unread message

Joe McGuckin

unread,
Feb 10, 2020, 5:12:24 PM2/10/20
to golang-nuts
Various sources say wait() waits until the internal counter reaches zero. Does it cause a real pause (e.g.: control passing to another goroutine?) Looking at the code, it just seems to loop endlessly waiting for the counter to reach zero. Is that somehow optimized away? Sitting in a tight loop waiting for a bunch of goroutines to exit seems like a waste of machine cycles...

Joe

Jesper Louis Andersen

unread,
Feb 10, 2020, 6:58:43 PM2/10/20
to Joe McGuckin, golang-nuts
There are two Wait() methods in the sync package. One is on the type Cond and one is on the type WaitGroup.

Assuming you mean waitgroup, the code uses the runtime call Semacquire which is a semaphore lock. In that case, you are not looping anymore, but waiting until said semaphore is released. It is released if a call to .Add reaches 0 (Note that .Done is Add(-1)).

Assuming you mean Cond, the code uses the runtime notify list primitive to park the goroutine until either Signal or Broadcast is called at which point execution continues.

If this doesn't answer your question, please do not hesitate to elaborate what your concern is.


On Mon, Feb 10, 2020 at 6:12 PM Joe McGuckin <mcgu...@gmail.com> wrote:
Various sources say wait() waits until the internal counter reaches zero. Does it cause a real pause (e.g.: control passing to another goroutine?) Looking at the code, it just seems to loop endlessly waiting for the counter to reach zero. Is that somehow optimized away? Sitting in a tight loop waiting for a bunch of goroutines to exit seems like a waste of machine cycles...

Joe

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4698ca4b-530e-4314-bd5d-c76a89e19a1a%40googlegroups.com.


--
J.
Reply all
Reply to author
Forward
0 new messages