Commit 0371d47f authored by Matthieu Martin's avatar Matthieu Martin Committed by Facebook Github Bot

Allow fibers Semaphore's Baton to signal during post

Summary:
This change has no effect for normal use of the semaphore.

With try_acquire (previous change), we now allow the callers to pass their own baton.
It's possible that the caller ends up not needing to use the `post`, and simply wants to signal the semaphore. It's basically useful in scenario where the caller wants to wait for the first of multiple events.
Current code would deadlock in this scenario, this fixes it.

Reviewed By: andriigrynenko

Differential Revision: D15090395

fbshipit-source-id: 8e3d73705ef3559717b7335f6a9e9ea8bed1cb17
parent c379a920
......@@ -19,25 +19,31 @@ namespace folly {
namespace fibers {
bool Semaphore::signalSlow() {
// If we signalled a release, notify the waitlist
auto waitListLock = waitList_.wlock();
auto& waitList = *waitListLock;
Baton* waiter = nullptr;
{
// If we signalled a release, notify the waitlist
auto waitListLock = waitList_.wlock();
auto& waitList = *waitListLock;
auto testVal = tokens_.load(std::memory_order_acquire);
if (testVal != 0) {
return false;
}
auto testVal = tokens_.load(std::memory_order_acquire);
if (testVal != 0) {
return false;
}
if (waitList.empty()) {
// If the waitlist is now empty, ensure the token count increments
// No need for CAS here as we will always be under the mutex
CHECK(tokens_.compare_exchange_strong(
testVal, testVal + 1, std::memory_order_relaxed));
} else {
// trigger waiter if there is one
waitList.front()->post();
if (waitList.empty()) {
// If the waitlist is now empty, ensure the token count increments
// No need for CAS here as we will always be under the mutex
CHECK(tokens_.compare_exchange_strong(
testVal, testVal + 1, std::memory_order_relaxed));
return true;
}
waiter = waitList.front();
waitList.pop();
}
// Trigger waiter if there is one
// Do it after releasing the waitList mutex, in case the waiter
// eagerly calls signal
waiter->post();
return true;
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment