https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103187
Bug ID: 103187 Summary: std::counting_semaphore::try_acquire_for does not unblock during wait duration Product: gcc Version: 11.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: s.zvyagin83 at gmail dot com Target Milestone: --- According to C++ standart https://eel.is/c++draft/thread.sema.cnt#18.2 try_acquire_for/until should block until counter is greater than zero or until timeout expires. But semaphores implemented with atomic_wait blocks for whole timeout even if semaphore released during wait. minimal repoduce code: g++ -std=c++20 -lpthread #include <thread> #include <semaphore> #include <time.h> #include <stdio.h> using namespace std::chrono_literals; int main() { std::binary_semaphore sem{0}; auto begin = std::chrono::steady_clock::now(); auto time = [&begin] { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-begin).count(); }; std::jthread jthr( [&sem, &time] { printf("[%ld] thread start\n", time()); std::this_thread::sleep_for(1s); printf("[%ld] sem.release\n", time()); sem.release(); }); printf("[%ld] sem.try_acquire_for\n", time()); if (sem.try_acquire_for(10s)) printf("[%ld] sem.acquired\n", time()); else printf("[%ld] failed to acquire sem\n", time()); } output: [0] sem.try_acquire_for [0] thread start [1000] sem.release [10000] sem.acquired POSIX semaphores with same code work correctly and unblock immediately when semaphore released g++ -std=c++20 -lpthread -D_GLIBCXX_USE_POSIX_SEMAPHORE=1 output: [0] sem.try_acquire_for [0] thread start [1000] sem.release [1000] sem.acquired