Imported Upstream version 1.57.0
[platform/upstream/boost.git] / libs / thread / test / sync / mutual_exclusion / locks / shared_lock / cons / time_point_pass.cpp
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 // Copyright (C) 2011 Vicente J. Botet Escriba
11 //
12 //  Distributed under the Boost Software License, Version 1.0. (See accompanying
13 //  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
14
15 // <boost/thread/locks.hpp>
16
17 // template <class Mutex> class shared_lock;
18
19 // template <class Clock, class Duration>
20 //   shared_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time);
21
22 #include <boost/thread/lock_types.hpp>
23 #include <boost/thread/shared_mutex.hpp>
24 #include <boost/thread/thread.hpp>
25 #include <boost/detail/lightweight_test.hpp>
26
27 boost::shared_mutex m;
28
29 typedef boost::chrono::steady_clock Clock;
30 typedef Clock::time_point time_point;
31 typedef Clock::duration duration;
32 typedef boost::chrono::milliseconds ms;
33 typedef boost::chrono::nanoseconds ns;
34
35 void f1()
36 {
37   time_point t0 = Clock::now();
38   // This test is spurious as it depends on the time the thread system switches the threads
39   boost::shared_lock<boost::shared_mutex> lk(m, Clock::now() + ms(300)+ms(1000));
40   BOOST_TEST(lk.owns_lock() == true);
41   time_point t1 = Clock::now();
42   ns d = t1 - t0 - ms(250);
43   // This test is spurious as it depends on the time the thread system switches the threads
44   BOOST_TEST(d < ns(50000000)+ms(1000)); // within 50ms
45 }
46
47 void f2()
48 {
49   time_point t0 = Clock::now();
50   boost::shared_lock<boost::shared_mutex> lk(m, Clock::now() + ms(250));
51   BOOST_TEST(lk.owns_lock() == false);
52   time_point t1 = Clock::now();
53   ns d = t1 - t0 - ms(250);
54   // This test is spurious as it depends on the time the thread system switches the threads
55   BOOST_TEST(d < ns(5000000)+ms(1000)); // within 5ms
56 }
57
58 int main()
59 {
60   {
61     m.lock();
62     boost::thread t(f1);
63     boost::this_thread::sleep_for(ms(250));
64     m.unlock();
65     t.join();
66   }
67   {
68     m.lock();
69     boost::thread t(f2);
70     boost::this_thread::sleep_for(ms(300)+ms(1000));
71     m.unlock();
72     t.join();
73   }
74
75   return boost::report_errors();
76 }
77