]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - test/std/thread/thread.threads/thread.thread.this/sleep_for.pass.cpp
Vendor import of libc++ trunk r302418:
[FreeBSD/FreeBSD.git] / test / std / 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 // UNSUPPORTED: libcpp-has-no-threads
11
12 // This test uses the POSIX header <sys/time.h> which Windows doesn't provide
13 // UNSUPPORTED: windows
14
15 // This test depends on signal behaviour until r210210, so some system libs
16 // don't pass.
17 //
18 // XFAIL: with_system_cxx_lib=macosx10.11
19 // XFAIL: with_system_cxx_lib=macosx10.10
20 // XFAIL: with_system_cxx_lib=macosx10.9
21 // XFAIL: with_system_cxx_lib=macosx10.8
22 // XFAIL: with_system_cxx_lib=macosx10.7
23
24 // <thread>
25
26 // template <class Rep, class Period>
27 //   void sleep_for(const chrono::duration<Rep, Period>& rel_time);
28
29 #include <thread>
30 #include <cstdlib>
31 #include <cassert>
32 #include <cstring>
33 #include <signal.h>
34 #include <sys/time.h>
35
36 void sig_action(int) {}
37
38 #include <iostream>
39 int main()
40 {
41     int ec;
42     struct sigaction action;
43     action.sa_handler = &sig_action;
44     sigemptyset(&action.sa_mask);
45     action.sa_flags = 0;
46
47     ec = sigaction(SIGALRM, &action, nullptr);
48     assert(!ec);
49
50     struct itimerval it;
51     std::memset(&it, 0, sizeof(itimerval));
52     it.it_value.tv_sec = 0;
53     it.it_value.tv_usec = 250000;
54     // This will result in a SIGALRM getting fired resulting in the nanosleep
55     // inside sleep_for getting EINTR.
56     ec = setitimer(ITIMER_REAL, &it, nullptr);
57     assert(!ec);
58
59     typedef std::chrono::system_clock Clock;
60     typedef Clock::time_point time_point;
61     typedef Clock::duration duration;
62     std::chrono::milliseconds ms(500);
63     time_point t0 = Clock::now();
64     std::this_thread::sleep_for(ms);
65     time_point t1 = Clock::now();
66     std::chrono::nanoseconds ns = (t1 - t0) - ms;
67     std::chrono::nanoseconds err = 5 * ms / 100;
68     // The time slept is within 5% of 500ms
69     assert(std::abs(ns.count()) < err.count());
70 }