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: libcpp-has-no-threads
10 
11 // ALLOW_RETRIES: 2
12 
13 // <mutex>
14 
15 // class mutex;
16 
17 // void lock();
18 
19 #include <mutex>
20 #include <thread>
21 #include <cstdlib>
22 #include <cassert>
23 
24 #include "test_macros.h"
25 
26 std::mutex m;
27 
28 typedef std::chrono::system_clock Clock;
29 typedef Clock::time_point time_point;
30 typedef Clock::duration duration;
31 typedef std::chrono::milliseconds ms;
32 typedef std::chrono::nanoseconds ns;
33 
34 #if !TEST_SLOW_HOST()
35 ms WaitTime = ms(250);
36 ms Tolerance = ms(50);
37 #else
38 ms WaitTime = ms(750);
39 ms Tolerance = ms(200);
40 #endif
41 
f()42 void f()
43 {
44     time_point t0 = Clock::now();
45     m.lock();
46     time_point t1 = Clock::now();
47     m.unlock();
48     ns d = t1 - t0 - WaitTime;
49     assert(d < Tolerance);  // within 50ms
50 }
51 
main(int,char **)52 int main(int, char**)
53 {
54     m.lock();
55     std::thread t(f);
56     std::this_thread::sleep_for(WaitTime);
57     m.unlock();
58     t.join();
59 
60   return 0;
61 }
62