From 5009049e96ecc8c6f5e8d147f6c93a3d645f195b Mon Sep 17 00:00:00 2001 From: Faruk Barotov Date: Fri, 24 Jan 2025 23:11:36 -0800 Subject: [PATCH] Fix a race in fibers::BatchSemaphore 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 --- folly/fibers/SemaphoreBase.cpp | 2 +- folly/fibers/test/BUCK | 9 ++++++ folly/fibers/test/BatchSemaphoreTest.cpp | 38 ++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 folly/fibers/test/BatchSemaphoreTest.cpp diff --git a/folly/fibers/SemaphoreBase.cpp b/folly/fibers/SemaphoreBase.cpp index a6ad891a7d9..5832f5e9bd8 100644 --- a/folly/fibers/SemaphoreBase.cpp +++ b/folly/fibers/SemaphoreBase.cpp @@ -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; diff --git a/folly/fibers/test/BUCK b/folly/fibers/test/BUCK index 396c9e2fd78..db1d9d1ea01 100644 --- a/folly/fibers/test/BUCK +++ b/folly/fibers/test/BUCK @@ -85,3 +85,12 @@ cpp_unittest( "//folly/synchronization/detail:sleeper", ], ) + +cpp_unittest( + name = "batch_semaphore_test", + srcs = ["BatchSemaphoreTest.cpp"], + deps = [ + "//folly/fibers:batch_semaphore", + "//folly/portability:gtest", + ], +) diff --git a/folly/fibers/test/BatchSemaphoreTest.cpp b/folly/fibers/test/BatchSemaphoreTest.cpp new file mode 100644 index 00000000000..25f0d5a2f52 --- /dev/null +++ b/folly/fibers/test/BatchSemaphoreTest.cpp @@ -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 +#include + +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; +}