Debian Codegraph @

libcxx/test/std/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.cons/mutex_try_to_lock.pass.cpp

raw
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 // UNSUPPORTED: no-threads
10 // UNSUPPORTED: c++03
11 // ALLOW_RETRIES: 2
12
13 // <mutex>
14
15 // template <class Mutex> class unique_lock;
16
17 // unique_lock(mutex_type& m, try_to_lock_t);
18
19 #include <cassert>
20 #include <chrono>
21 #include <cstdlib>
22 #include <mutex>
23 #include <thread>
24
25 #include "make_test_thread.h"
26 #include "test_macros.h"
27
28 std::mutex m;
29
30 typedef std::chrono::system_clock Clock;
31 typedef Clock::time_point time_point;
32 typedef Clock::duration duration;
33 typedef std::chrono::milliseconds ms;
34 typedef std::chrono::nanoseconds ns;
35
36 void f()
37 {
38 time_point t0 = Clock::now();
39 {
40 std::unique_lock<std::mutex> lk(m, std::try_to_lock);
41 assert(lk.owns_lock() == false);
42 }
43 {
44 std::unique_lock<std::mutex> lk(m, std::try_to_lock);
45 assert(lk.owns_lock() == false);
46 }
47 {
48 std::unique_lock<std::mutex> lk(m, std::try_to_lock);
49 assert(lk.owns_lock() == false);
50 }
51 while (true)
52 {
53 std::unique_lock<std::mutex> lk(m, std::try_to_lock);
54 if (lk.owns_lock())
55 break;
56 }
57 time_point t1 = Clock::now();
58 ns d = t1 - t0 - ms(250);
59 assert(d < ms(200)); // within 200ms
60 }
61
62 int main(int, char**)
63 {
64 m.lock();
65 std::thread t = support::make_test_thread(f);
66 std::this_thread::sleep_for(ms(250));
67 m.unlock();
68 t.join();
69
70 return 0;
71 }