Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
Howard Hinnant | f5256e1 | 2010-05-11 21:36:01 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 4 | // |
Howard Hinnant | b64f8b0 | 2010-11-16 22:09:02 +0000 | [diff] [blame] | 5 | // This file is dual licensed under the MIT and the University of Illinois Open |
| 6 | // Source Licenses. See LICENSE.TXT for details. |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
Jonathan Roelofs | 8d86b2e | 2014-09-05 19:45:05 +0000 | [diff] [blame] | 9 | // |
| 10 | // UNSUPPORTED: libcpp-has-no-threads |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 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 | |
| 31 | void 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 Hinnant | 66a48c5 | 2013-02-06 20:25:56 +0000 | [diff] [blame] | 39 | assert(d < ms(25)); // within 25ms |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 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 | |
| 62 | int 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 | } |