Home | History | Annotate | Download | only in thread.lock.unique.locking
      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 // <mutex>
     11 
     12 // template <class Mutex> class unique_lock;
     13 
     14 // void lock();
     15 
     16 #include <mutex>
     17 #include <thread>
     18 #include <cstdlib>
     19 #include <cassert>
     20 
     21 std::mutex m;
     22 
     23 typedef std::chrono::system_clock Clock;
     24 typedef Clock::time_point time_point;
     25 typedef Clock::duration duration;
     26 typedef std::chrono::milliseconds ms;
     27 typedef std::chrono::nanoseconds ns;
     28 
     29 void f()
     30 {
     31     std::unique_lock<std::mutex> lk(m, std::defer_lock);
     32     time_point t0 = Clock::now();
     33     lk.lock();
     34     time_point t1 = Clock::now();
     35     assert(lk.owns_lock() == true);
     36     ns d = t1 - t0 - ms(250);
     37     assert(d < ns(2500000));  // within 2.5ms
     38     try
     39     {
     40         lk.lock();
     41         assert(false);
     42     }
     43     catch (std::system_error& e)
     44     {
     45         assert(e.code().value() == EDEADLK);
     46     }
     47     lk.unlock();
     48     lk.release();
     49     try
     50     {
     51         lk.lock();
     52         assert(false);
     53     }
     54     catch (std::system_error& e)
     55     {
     56         assert(e.code().value() == EPERM);
     57     }
     58 }
     59 
     60 int main()
     61 {
     62     m.lock();
     63     std::thread t(f);
     64     std::this_thread::sleep_for(ms(250));
     65     m.unlock();
     66     t.join();
     67 }
     68