this_thread.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 <__thread/support.h>
  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. _LIBCPP_EXPORTED_FROM_ABI void sleep_for(const chrono::nanoseconds& __ns);
  26. template <class _Rep, class _Period>
  27. _LIBCPP_HIDE_FROM_ABI void sleep_for(const chrono::duration<_Rep, _Period>& __d) {
  28. if (__d > chrono::duration<_Rep, _Period>::zero()) {
  29. // The standard guarantees a 64bit signed integer resolution for nanoseconds,
  30. // so use INT64_MAX / 1e9 as cut-off point. Use a constant to avoid <climits>
  31. // and issues with long double folding on PowerPC with GCC.
  32. _LIBCPP_CONSTEXPR chrono::duration<long double> __max = chrono::duration<long double>(9223372036.0L);
  33. chrono::nanoseconds __ns;
  34. if (__d < __max) {
  35. __ns = chrono::duration_cast<chrono::nanoseconds>(__d);
  36. if (__ns < __d)
  37. ++__ns;
  38. } else
  39. __ns = chrono::nanoseconds::max();
  40. this_thread::sleep_for(__ns);
  41. }
  42. }
  43. template <class _Clock, class _Duration>
  44. _LIBCPP_HIDE_FROM_ABI void sleep_until(const chrono::time_point<_Clock, _Duration>& __t) {
  45. mutex __mut;
  46. condition_variable __cv;
  47. unique_lock<mutex> __lk(__mut);
  48. while (_Clock::now() < __t)
  49. __cv.wait_until(__lk, __t);
  50. }
  51. template <class _Duration>
  52. inline _LIBCPP_HIDE_FROM_ABI void sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t) {
  53. this_thread::sleep_for(__t - chrono::steady_clock::now());
  54. }
  55. inline _LIBCPP_HIDE_FROM_ABI void yield() _NOEXCEPT { __libcpp_thread_yield(); }
  56. } // namespace this_thread
  57. _LIBCPP_END_NAMESPACE_STD
  58. _LIBCPP_POP_MACROS
  59. #endif // _LIBCPP___THREAD_THIS_THREAD_H