1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // XFAIL: libcpp-no-exceptions 11 // UNSUPPORTED: libcpp-has-no-threads 12 13 // <mutex> 14 15 // template <class Mutex> class unique_lock; 16 17 // void lock(); 18 19 #include <mutex> 20 #include <thread> 21 #include <cstdlib> 22 #include <cassert> 23 24 std::mutex m; 25 26 typedef std::chrono::system_clock Clock; 27 typedef Clock::time_point time_point; 28 typedef Clock::duration duration; 29 typedef std::chrono::milliseconds ms; 30 typedef std::chrono::nanoseconds ns; 31 32 void f() 33 { 34 std::unique_lock<std::mutex> lk(m, std::defer_lock); 35 time_point t0 = Clock::now(); 36 lk.lock(); 37 time_point t1 = Clock::now(); 38 assert(lk.owns_lock() == true); 39 ns d = t1 - t0 - ms(250); 40 assert(d < ms(25)); // within 25ms 41 try 42 { 43 lk.lock(); 44 assert(false); 45 } 46 catch (std::system_error& e) 47 { 48 assert(e.code().value() == EDEADLK); 49 } 50 lk.unlock(); 51 lk.release(); 52 try 53 { 54 lk.lock(); 55 assert(false); 56 } 57 catch (std::system_error& e) 58 { 59 assert(e.code().value() == EPERM); 60 } 61 } 62 63 int main() 64 { 65 m.lock(); 66 std::thread t(f); 67 std::this_thread::sleep_for(ms(250)); 68 m.unlock(); 69 t.join(); 70 } 71