this_thread.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP___THREAD_THIS_THREAD_H
  10. #define _LIBCPP___THREAD_THIS_THREAD_H
  11. #include <__chrono/steady_clock.h>
  12. #include <__chrono/time_point.h>
  13. #include <__condition_variable/condition_variable.h>
  14. #include <__config>
  15. #include <__mutex/mutex.h>
  16. #include <__mutex/unique_lock.h>
  17. #include <__threading_support>
  18. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  19. # pragma GCC system_header
  20. #endif
  21. _LIBCPP_PUSH_MACROS
  22. #include <__undef_macros>
  23. _LIBCPP_BEGIN_NAMESPACE_STD
  24. namespace this_thread
  25. {
  26. _LIBCPP_EXPORTED_FROM_ABI void sleep_for(const chrono::nanoseconds& __ns);
  27. template <class _Rep, class _Period>
  28. _LIBCPP_HIDE_FROM_ABI void
  29. sleep_for(const chrono::duration<_Rep, _Period>& __d)
  30. {
  31. if (__d > chrono::duration<_Rep, _Period>::zero())
  32. {
  33. // The standard guarantees a 64bit signed integer resolution for nanoseconds,
  34. // so use INT64_MAX / 1e9 as cut-off point. Use a constant to avoid <climits>
  35. // and issues with long double folding on PowerPC with GCC.
  36. _LIBCPP_CONSTEXPR chrono::duration<long double> __max =
  37. chrono::duration<long double>(9223372036.0L);
  38. chrono::nanoseconds __ns;
  39. if (__d < __max)
  40. {
  41. __ns = chrono::duration_cast<chrono::nanoseconds>(__d);
  42. if (__ns < __d)
  43. ++__ns;
  44. }
  45. else
  46. __ns = chrono::nanoseconds::max();
  47. this_thread::sleep_for(__ns);
  48. }
  49. }
  50. template <class _Clock, class _Duration>
  51. _LIBCPP_HIDE_FROM_ABI void
  52. sleep_until(const chrono::time_point<_Clock, _Duration>& __t)
  53. {
  54. mutex __mut;
  55. condition_variable __cv;
  56. unique_lock<mutex> __lk(__mut);
  57. while (_Clock::now() < __t)
  58. __cv.wait_until(__lk, __t);
  59. }
  60. template <class _Duration>
  61. inline _LIBCPP_INLINE_VISIBILITY
  62. void
  63. sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t)
  64. {
  65. this_thread::sleep_for(__t - chrono::steady_clock::now());
  66. }
  67. inline _LIBCPP_INLINE_VISIBILITY
  68. void yield() _NOEXCEPT {__libcpp_thread_yield();}
  69. } // namespace this_thread
  70. _LIBCPP_END_NAMESPACE_STD
  71. _LIBCPP_POP_MACROS
  72. #endif // _LIBCPP___THREAD_THIS_THREAD_H