Skip to content

Commit

Permalink
Fix a race in fibers::BatchSemaphore
Browse files Browse the repository at this point in the history
Summary: D66114255 fixed a data race in `fibers::Semaphore` occuring due to lack of 'happens-before' signal-wait synchronization. The very same issue exists in `fibers::BatchedSemaphore` which I came across today in a flaky unit test. Hence porting the fix.

Reviewed By: Gownta

Differential Revision: D68594868

fbshipit-source-id: 752a7b15198015928a7fe040fecc8b3c9e56a889
  • Loading branch information
Faruk Barotov authored and facebook-github-bot committed Jan 25, 2025
1 parent 2e164dc commit cd83999
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion third-party/folly/src/folly/fibers/SemaphoreBase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ bool SemaphoreBase::signalSlow(int64_t tokens) {
// waitlist, ensure the token count increments. No need for CAS here as
// we will always be under the mutex
if (tokens_.compare_exchange_strong(
testVal, testVal + tokens, std::memory_order_relaxed)) {
testVal, testVal + tokens, std::memory_order_release)) {
return true;
}
continue;
Expand Down
38 changes: 38 additions & 0 deletions third-party/folly/src/folly/fibers/test/BatchSemaphoreTest.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include <folly/fibers/BatchSemaphore.h>
#include <folly/portability/GTest.h>

TEST(BatchSemaphoreTest, WaitSignalSynchronization) {
folly::fibers::BatchSemaphore sem{0};

int64_t data = 0;
folly::relaxed_atomic_bool signalled = false;

std::jthread t{[&]() {
while (!signalled) {
std::this_thread::yield();
}

sem.wait(1);
EXPECT_NE(data, 0);
}};

data = 1;
sem.signal(1);
signalled = true;
}

0 comments on commit cd83999

Please sign in to comment.