Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / libc++ / trunk / test / thread / thread.threads / thread.thread.this / sleep_for.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 // <thread>
11
12 // template <class Rep, class Period>
13 //   void sleep_for(const chrono::duration<Rep, Period>& rel_time);
14
15 #include <thread>
16 #include <cstdlib>
17 #include <cassert>
18 #include <signal.h>
19 #include <sys/time.h>
20
21 int main()
22 {
23     int ec;
24     struct sigaction action;
25     action.sa_handler = [](int) {};
26     sigemptyset(&action.sa_mask);
27     action.sa_flags = 0;
28
29     ec = sigaction(SIGALRM, &action, nullptr);
30     assert(!ec);
31
32     struct itimerval it;
33     it.it_interval = { 0 };
34     it.it_value.tv_sec = 0;
35     it.it_value.tv_usec = 250000;
36     // This will result in a SIGALRM getting fired resulting in the nanosleep
37     // inside sleep_for getting EINTR.
38     ec = setitimer(ITIMER_REAL, &it, nullptr);
39     assert(!ec);
40
41     typedef std::chrono::system_clock Clock;
42     typedef Clock::time_point time_point;
43     typedef Clock::duration duration;
44     std::chrono::milliseconds ms(500);
45     time_point t0 = Clock::now();
46     std::this_thread::sleep_for(ms);
47     time_point t1 = Clock::now();
48     std::chrono::nanoseconds ns = (t1 - t0) - ms;
49     std::chrono::nanoseconds err = 5 * ms / 100;
50     // The time slept is within 5% of 500ms
51     assert(std::abs(ns.count()) < err.count());
52 }