-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Issue originally posted by @bakkot in lucacasonato/proposal-semaphore#1
One of the questions in the readme:
Should the
Semaphorehave a way to query the number of tokens available?
I think definitely yes.
Moreover I think there should be a way to synchronously acquire a token when one is available, as in
if (semaphore.tokens > 0) {
using permit = semaphore.acquireSyncOrFail();
// do work
} else {
throw "could not do work right now"
}or
if (semaphore.tokens > 0) {
semaphore.withSyncOrFail(syncCallback);
}The await semaphore.acquire() construct is convenient in places which are already async, but not all places can afford to be async.
Unfortunately this pattern fits awkwardly with cross-thread semaphores, because someone can in theory acquire a token between when you check if any are available and when you call acquireSyncOrFail. But as long as acquireSyncOrFail is atomic, that just gives you an error, not a race.
Maybe this is what you're getting at with the "try acquire" possibility raised in the readme, if you're suggesting that such a method be synchronous, but I think it's important that it throw rather than returning null. Otherwise it's too easy to write using permit = semaphore.tryAcquire() and not notice that it failed to acquire the token.