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 // FLAKY_TEST. 13 14 // <mutex> 15 16 // class timed_mutex; 17 18 // template <class Rep, class Period> 19 // unique_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time); 20 21 #include <mutex> 22 #include <thread> 23 #include <cstdlib> 24 #include <cassert> 25 26 std::timed_mutex m; 27 28 typedef std::chrono::steady_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 f1()34void f1() 35 { 36 time_point t0 = Clock::now(); 37 std::unique_lock<std::timed_mutex> lk(m, ms(300)); 38 assert(lk.owns_lock() == true); 39 time_point t1 = Clock::now(); 40 ns d = t1 - t0 - ms(250); 41 assert(d < ms(50)); // within 50ms 42 } 43 f2()44void f2() 45 { 46 time_point t0 = Clock::now(); 47 std::unique_lock<std::timed_mutex> lk(m, ms(250)); 48 assert(lk.owns_lock() == false); 49 time_point t1 = Clock::now(); 50 ns d = t1 - t0 - ms(250); 51 assert(d < ms(50)); // within 50ms 52 } 53 main()54int main() 55 { 56 { 57 m.lock(); 58 std::thread t(f1); 59 std::this_thread::sleep_for(ms(250)); 60 m.unlock(); 61 t.join(); 62 } 63 { 64 m.lock(); 65 std::thread t(f2); 66 std::this_thread::sleep_for(ms(300)); 67 m.unlock(); 68 t.join(); 69 } 70 } 71