Debian Codegraph @

libstdc++-v3/testsuite/30_threads/semaphore/try_acquire_for.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2 //
3 // This file is part of the GNU ISO C++ Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
7 // any later version.
8
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // You should have received a copy of the GNU General Public License along
15 // with this library; see the file COPYING3. If not see
16 // <http://www.gnu.org/licenses/>.
17
18 // { dg-do run { target c++20 } }
19 // { dg-additional-options "-pthread" { target pthread } }
20 // { dg-require-gthreads "" }
21 // { dg-add-options libatomic }
22
23 #include <semaphore>
24 #include <chrono>
25 #include <thread>
26 #include <atomic>
27 #include <testsuite_hooks.h>
28
29 void test01()
30 {
31 using namespace std::chrono_literals;
32 std::counting_semaphore<10> s(2);
33 s.acquire();
34
35 auto const dur = 250ms;
36 {
37 auto const t0 = std::chrono::steady_clock::now();
38 VERIFY( s.try_acquire_for(dur) );
39 auto const diff = std::chrono::steady_clock::now() - t0;
40 VERIFY( diff < dur );
41 }
42
43 {
44 auto const t0 = std::chrono::steady_clock::now();
45 VERIFY( !s.try_acquire_for(dur) );
46 auto const diff = std::chrono::steady_clock::now() - t0;
47 VERIFY( diff >= dur );
48 }
49 }
50
51 void test02()
52 {
53 using namespace std::chrono_literals;
54 std::binary_semaphore s(1);
55 std::atomic<int> a(0), b(0);
56 std::thread t([&] {
57 a.wait(0);
58 auto const dur = 250ms;
59 VERIFY( !s.try_acquire_for(dur) );
60 b++;
61 b.notify_one();
62
63 a.wait(1);
64 VERIFY( s.try_acquire_for(dur) );
65 b++;
66 b.notify_one();
67 });
68 t.detach();
69
70 s.acquire();
71 a++;
72 a.notify_one();
73 b.wait(0);
74 s.release();
75 a++;
76 a.notify_one();
77
78 b.wait(1);
79 }
80
81 void
82 test03()
83 {
84 using tick = std::chrono::system_clock::duration::period;
85 using halftick = std::ratio<tick::num, 2 * tick::den>;
86 std::chrono::duration<long long, halftick> timeout(1);
87 std::binary_semaphore s(1);
88
89 // Using higher resolution than chrono::system_clock should compile:
90 s.try_acquire_for(timeout);
91 }
92
93 int main()
94 {
95 test01();
96 test02();
97 test03();
98 }