]> git.ipfire.org Git - thirdparty/gcc.git/blame - libstdc++-v3/testsuite/30_threads/semaphore/try_acquire_for.cc
Update copyright years.
[thirdparty/gcc.git] / libstdc++-v3 / testsuite / 30_threads / semaphore / try_acquire_for.cc
CommitLineData
7adcbafe 1// Copyright (C) 2020-2022 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
18// { dg-options "-std=gnu++2a -pthread" }
19// { dg-do run { target c++2a } }
20// { dg-require-effective-target pthread }
21// { dg-require-gthreads "" }
71dc5ae5 22// { dg-add-options libatomic }
83a1beee
TR
23
24#include <semaphore>
25#include <chrono>
26#include <thread>
27#include <atomic>
28#include <testsuite_hooks.h>
29
30void test01()
31{
32 using namespace std::chrono_literals;
33 std::counting_semaphore<10> s(2);
34 s.acquire();
35
36 auto const dur = 250ms;
37 {
38 auto const t0 = std::chrono::steady_clock::now();
39 VERIFY( s.try_acquire_for(dur) );
40 auto const diff = std::chrono::steady_clock::now() - t0;
41 VERIFY( diff < dur );
42 }
43
44 {
45 auto const t0 = std::chrono::steady_clock::now();
46 VERIFY( !s.try_acquire_for(dur) );
47 auto const diff = std::chrono::steady_clock::now() - t0;
48 VERIFY( diff >= dur );
49 }
50}
51
52void test02()
53{
54 using namespace std::chrono_literals;
55 std::binary_semaphore s(1);
56 std::atomic<int> a(0), b(0);
57 std::thread t([&] {
58 a.wait(0);
59 auto const dur = 250ms;
60 VERIFY( !s.try_acquire_for(dur) );
61 b++;
62 b.notify_one();
63
64 a.wait(1);
65 VERIFY( s.try_acquire_for(dur) );
66 b++;
67 b.notify_one();
68 });
69 t.detach();
70
71 s.acquire();
72 a++;
73 a.notify_one();
74 b.wait(0);
75 s.release();
76 a++;
77 a.notify_one();
78
79 b.wait(1);
80}
81
82int main()
83{
84 test01();
85 test02();
86}