Open wilkice opened 1 year ago
This program should return immediately after compare request weight with size.
Why?
The documented semantics of Acquire
are: “Acquire
acquires the semaphore with a weight of n
, blocking until resources are available or ctx
is done.” Returning early for another reason would add yet another condition there.
Moreover, for callers that want the early-return behavior, it is easy enough to save the original n
passed to NewWeighted
and do the comparison on the caller side before calling Acquire
.
Acquire acquires the semaphore with a weight of n, blocking until resources are available or ctx is done
Yes, I agree this. If request weight is not larger than size
, wait for resource or ctx
is ok because there is chance for this request to be accepted.
But if the request weight is larger than size
, this request won't be accepted at any time. So what's the point of waiting for ctx
even when we know it already fails?
if n > s.size {
// Don't make other Acquire calls block on one that's doomed to fail.
s.mu.Unlock()
<-ctx.Done()
return ctx.Err()
}
fwiw, golang.org/x/sync/rate.Limiter.WaitN
, which is similar to a semaphore will error on exceeding max size
I am very agree with darcy.If I did not set ctx WithTimeout , there will be a Memory leak. for example code: https://go.dev/play/p/roy3vs1s4OD sem.Acquire(ctx, 1000)will never return ,that will get a Memory leak. It is very dangerous
line 51 <-ctx.Done()
when using context.TODO()
or context.Background()
, it will block forever if weight > size
godoc WorkerPool example with sem.Acquire(ctx, 1)
changed to sem.Acquire(ctx, 9) // GOMAXPROCS=8
https://go.dev/play/p/33E7JxU0zyh
https://pkg.go.dev/golang.org/x/sync/semaphore#example-package-WorkerPool
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
https://go.dev/play/p/hqcrWEMRu-e
What did you expect to see?
This program should return immediately after compare request weight with size. For the request weight, 1000, is larger than size, 8. The request won't be fulfilled at any time.
source code: https://cs.opensource.google/go/x/sync/+/master:semaphore/semaphore.go;l=48-53;drc=43a5402ce75a95522677f77c619865d66b8c57ab
I think source code at line 51 should by removed
What did you see instead?
Waited 10 second before exit.