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 // UNSUPPORTED: libcpp-has-no-threads 11 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 23 std::mutex m; 24 25 typedef std::chrono::system_clock Clock; 26 typedef Clock::time_point time_point; 27 typedef Clock::duration duration; 28 typedef std::chrono::milliseconds ms; 29 typedef std::chrono::nanoseconds ns; 30 f()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); 39 assert(d < ms(25)); // within 25ms 40 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 main()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 } 70