libxr
Embedded C++ framework for bare-metal, RTOS and Linux
Loading...
Searching...
No Matches
thread.cpp
1#include "thread.hpp"
2
3#include <cerrno>
4
5#include "libxr_def.hpp"
6#include "monotonic_time.hpp"
7#include "timebase.hpp"
8
9using namespace LibXR;
10
11extern struct timespec libxr_linux_start_time_spec;
12
13Thread Thread::Current(void) { return Thread(pthread_self()); }
14
15void Thread::Sleep(uint32_t milliseconds)
16{
17 timespec ts = MonotonicTime::RelativeFromMilliseconds(milliseconds);
18 while (clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts) == EINTR)
19 {
20 }
21}
22
23void Thread::SleepUntil(MillisecondTimestamp& last_wakeup_time, uint32_t time_to_sleep)
24{
25 last_wakeup_time = last_wakeup_time + time_to_sleep;
26
27 const timespec ts =
28 MonotonicTime::AddMilliseconds(libxr_linux_start_time_spec, last_wakeup_time);
29
30 while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, nullptr) == EINTR)
31 {
32 }
33}
34
36
37void Thread::Yield() { sched_yield(); }
38
40{
41 return pthread_join(thread_handle_, nullptr) == 0 ? ErrorCode::OK : ErrorCode::FAILED;
42}
毫秒时间戳 / Millisecond timestamp
线程管理类,封装 POSIX 线程创建和调度 Thread management class encapsulating POSIX thread creation and scheduling
Definition thread.hpp:19
static void SleepUntil(MillisecondTimestamp &last_wakeup_time, uint32_t time_to_sleep)
让线程休眠直到指定时间点 Puts the thread to sleep until a specified time
Definition thread.cpp:23
Thread()
默认构造函数,初始化空线程 Default constructor initializing an empty thread
Definition thread.hpp:39
static uint32_t GetTime()
获取当前系统时间(毫秒) Gets the current system time in milliseconds
Definition thread.cpp:35
static Thread Current(void)
获取当前线程对象 Gets the current thread object
Definition thread.cpp:13
ErrorCode Join()
Waits for this POSIX thread to terminate and releases its resources.
Definition thread.cpp:39
static void Sleep(uint32_t milliseconds)
让线程进入休眠状态 Puts the thread to sleep
Definition thread.cpp:15
static void Yield()
让出 CPU 以执行其他线程 Yields CPU execution to allow other threads to run
Definition thread.cpp:37
static MillisecondTimestamp GetMilliseconds()
获取当前时间的毫秒级时间戳。 Gets the current timestamp in milliseconds.
LibXR 命名空间 / LibXR namespace.
Definition ch32_can.hpp:14
ErrorCode
定义错误码枚举 / Defines an enumeration for error codes
@ FAILED
操作失败 / Operation failed
@ OK
操作成功 / Operation successful