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