blob: f5408df981992f5600290261c70303a989ce901a [file] [log] [blame]
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00001//===----------------------------------------------------------------------===//
2//
Howard Hinnantf5256e12010-05-11 21:36:01 +00003// The LLVM Compiler Infrastructure
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00004//
Howard Hinnantb64f8b02010-11-16 22:09:02 +00005// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00007//
8//===----------------------------------------------------------------------===//
Jonathan Roelofs8d86b2e2014-09-05 19:45:05 +00009//
10// UNSUPPORTED: libcpp-has-no-threads
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000011
12// <mutex>
13
14// template <class Mutex> class unique_lock;
15
16// void lock();
17
18#include <mutex>
19#include <thread>
20#include <cstdlib>
21#include <cassert>
22
23std::mutex m;
24
25typedef std::chrono::system_clock Clock;
26typedef Clock::time_point time_point;
27typedef Clock::duration duration;
28typedef std::chrono::milliseconds ms;
29typedef std::chrono::nanoseconds ns;
30
31void f()
32{
33 std::unique_lock<std::mutex> lk(m, std::defer_lock);
34 time_point t0 = Clock::now();
35 lk.lock();
36 time_point t1 = Clock::now();
37 assert(lk.owns_lock() == true);
38 ns d = t1 - t0 - ms(250);
Howard Hinnant66a48c52013-02-06 20:25:56 +000039 assert(d < ms(25)); // within 25ms
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000040 try
41 {
42 lk.lock();
43 assert(false);
44 }
45 catch (std::system_error& e)
46 {
47 assert(e.code().value() == EDEADLK);
48 }
49 lk.unlock();
50 lk.release();
51 try
52 {
53 lk.lock();
54 assert(false);
55 }
56 catch (std::system_error& e)
57 {
58 assert(e.code().value() == EPERM);
59 }
60}
61
62int main()
63{
64 m.lock();
65 std::thread t(f);
66 std::this_thread::sleep_for(ms(250));
67 m.unlock();
68 t.join();
69}