sync: document guidance on Cond.Broadcast regarding holding the lock

As currently written, the documentation provides no guidance
on whether the lock should be held and seems to imply
that it does not really matter.

However, it does matter. In a heavily loaded production system,
there might be a million goroutines waiting on the condition,
calling Broadcast while holding the lock can cost ~100ms
of synchronous time notifying each of the waiters
(none of which can run anyways since the lock is still held).

At least surface the O(N) cost of Broadcast more clearly.

Change-Id: Ib1c7896826b0753cb79f3a62a3bace7612e58dcf
Reviewed-on: https://go-review.googlesource.com/c/go/+/752480
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Rondale Sidbury <rondale.sidbury@gmail.com>
This commit is contained in:
Joe Tsai 2026-03-06 13:06:50 -08:00 committed by Joseph Tsai
parent 52fd498a96
commit 1225feb0da

View file

@ -86,8 +86,10 @@ func (c *Cond) Signal() {
// Broadcast wakes all goroutines waiting on c.
//
// It is allowed but not required for the caller to hold c.L
// during the call.
// It is allowed but not required for the caller to hold c.L during the call.
// The time it takes to run Broadcast is proportional to the number of waiting goroutines;
// be aware that holding the lock across a call to Broadcast
// will extend the amount of time that the lock is held.
func (c *Cond) Broadcast() {
c.checker.check()
runtime_notifyListNotifyAll(&c.notify)