thread.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Distributed under the Boost Software License, Version 1.0. (See
  2. // accompanying file LICENSE_1_0.txt or copy at
  3. // http://www.boost.org/LICENSE_1_0.txt)
  4. // (C) Copyright 2011 Vicente J. Botet Escriba
  5. #ifndef BOOST_THREAD_V2_THREAD_HPP
  6. #define BOOST_THREAD_V2_THREAD_HPP
  7. #include <boost/thread/detail/config.hpp>
  8. #ifdef BOOST_THREAD_USES_CHRONO
  9. #include <boost/chrono/system_clocks.hpp>
  10. #include <boost/chrono/ceil.hpp>
  11. #endif
  12. #include <boost/thread/condition_variable.hpp>
  13. #include <boost/thread/lock_types.hpp>
  14. namespace boost
  15. {
  16. namespace this_thread
  17. {
  18. #ifdef BOOST_THREAD_USES_CHRONO
  19. template <class Clock, class Duration>
  20. void sleep_until(const chrono::time_point<Clock, Duration>& t)
  21. {
  22. using namespace chrono;
  23. mutex mut;
  24. condition_variable cv;
  25. unique_lock<mutex> lk(mut);
  26. while (Clock::now() < t)
  27. cv.wait_until(lk, t);
  28. }
  29. #ifdef BOOST_THREAD_SLEEP_FOR_IS_STEADY
  30. template <class Rep, class Period>
  31. void sleep_for(const chrono::duration<Rep, Period>& d)
  32. {
  33. using namespace chrono;
  34. if (d > duration<Rep, Period>::zero())
  35. {
  36. duration<long double> Max = nanoseconds::max BOOST_PREVENT_MACRO_SUBSTITUTION ();
  37. nanoseconds ns;
  38. if (d < Max)
  39. {
  40. ns = duration_cast<nanoseconds>(d);
  41. if (ns < d)
  42. ++ns;
  43. }
  44. else
  45. ns = nanoseconds:: max BOOST_PREVENT_MACRO_SUBSTITUTION ();
  46. sleep_for(ns);
  47. }
  48. }
  49. template <class Duration>
  50. inline BOOST_SYMBOL_VISIBLE
  51. void sleep_until(const chrono::time_point<chrono::steady_clock, Duration>& t)
  52. {
  53. using namespace chrono;
  54. sleep_for(t - steady_clock::now());
  55. }
  56. #else
  57. template <class Rep, class Period>
  58. void sleep_for(const chrono::duration<Rep, Period>& d)
  59. {
  60. using namespace chrono;
  61. if (d > duration<Rep, Period>::zero())
  62. {
  63. steady_clock::time_point c_timeout = steady_clock::now() + ceil<nanoseconds>(d);
  64. sleep_until(c_timeout);
  65. }
  66. }
  67. #endif
  68. #endif
  69. }
  70. }
  71. #endif