MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
Thread.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 Contributors to the Media eXchange Layer project.
2// SPDX-License-Identifier: Apache-2.0
3
5#include <cerrno>
6#include <sched.h>
7#include <mxl/platform.h>
9
10namespace mxl::lib
11{
12 namespace this_thread
13 {
14 void yield() noexcept
15 {
16 ::sched_yield();
17 }
18
19 void yieldProcessor() noexcept
20 {
21#if defined(__i386__) || defined(__x86_64__)
22 __builtin_ia32_pause();
23#elif defined(__ARM_ARCH) && (__ARM_ARCH >= 7)
24 asm volatile("dmb ish" ::: "memory");
25#else
26 // At least emulate the side effect of a compiler
27 // read/write barrier.
28 asm volatile("" ::: "memory")
29#endif
30 }
31
33 Duration sleep(Duration duration, [[maybe_unused]] Clock clock) noexcept
34 {
35 auto const sleepTime = asTimeSpec(duration);
36 std::timespec remainder;
37
38 auto const req = &sleepTime;
39 auto const rem = &remainder;
40
41#if defined(__linux__)
42 auto const result = ::clock_nanosleep(detail::clockToId(clock), 0, req, rem);
43 errno = result;
44#elif defined(__APPLE__)
45 auto const result = ::nanosleep(req, rem);
46#else
47# pragma GCC error No this_thread::sleep() implementation available for the current platform.
48#endif
49 // Please be aware that nanosleep() and clock_nanosleep() have
50 // different domains for their return value, but in either case
51 // a value of 0 means the call completed successfully.
52 return (result == 0) ? Duration{} : asDuration(remainder);
53 }
54
56 int sleepUntil(Timepoint timepoint, Clock clock) noexcept
57 {
58#if defined(__linux__)
59 auto const sleepTime = asTimeSpec(timepoint);
60 auto const result = ::clock_nanosleep(detail::clockToId(clock), TIMER_ABSTIME, &sleepTime, nullptr);
61 return result;
62#elif defined(__APPLE__)
63
64 auto const now = currentTime(clock);
65 if (timepoint > now)
66 {
67 auto const sleepTime = asTimeSpec(timepoint - now);
68 auto const result = ::nanosleep(&sleepTime, nullptr);
69 if (result)
70 {
71 return errno;
72 }
73 }
74 return 0;
75#else
76# pragma GCC error No this_thread::sleepUntil() implementation available for the current platform.
77#endif
78 }
79 }
80}
constexpr clockid_t clockToId(Clock clock) noexcept
int sleepUntil(Timepoint timepoint, Clock clock=Clock::Realtime) noexcept
Definition Thread.cpp:56
void yield() noexcept
Definition Thread.cpp:14
Duration sleep(Duration duration, Clock clock=Clock::Realtime) noexcept
Definition Thread.cpp:33
void yieldProcessor() noexcept
Definition Thread.cpp:19
constexpr std::timespec asTimeSpec(Timepoint timepoint) noexcept
Definition Timing.hpp:241
constexpr Duration asDuration(std::timespec const &duration) noexcept
Definition Timing.hpp:385
#define MXL_EXPORT
Definition platform.h:9
auto const now
auto const currentTime
Definition test_time.cpp:58