]>
Commit | Line | Data |
---|---|---|
a945c346 | 1 | // Copyright (C) 2020-2024 Free Software Foundation, Inc. |
83a1beee TR |
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 | ||
0ff31212 JW |
18 | // { dg-do run { target c++20 } } |
19 | // { dg-additional-options "-pthread" { target pthread } } | |
83a1beee | 20 | // { dg-require-gthreads "" } |
71dc5ae5 | 21 | // { dg-add-options libatomic } |
83a1beee TR |
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 | int main() | |
82 | { | |
83 | test01(); | |
84 | test02(); | |
85 | } |