libxr
Embedded C++ framework for bare-metal, RTOS and Linux
Loading...
Searching...
No Matches
LibXR::Thread Class Reference

线程管理类,封装 POSIX 线程创建和调度 Thread management class encapsulating POSIX thread creation and scheduling More...

#include <thread.hpp>

Public Types

enum class  Priority : uint8_t {
  IDLE , LOW , MEDIUM , HIGH ,
  REALTIME , NUMBER
}
 线程优先级枚举 Enumeration for thread priorities More...
 

Public Member Functions

 Thread ()
 默认构造函数,初始化空线程 Default constructor initializing an empty thread
 
 Thread (libxr_thread_handle handle)
 通过 POSIX 线程句柄创建线程对象 Constructor to create a thread object from a POSIX thread handle
 
template<typename ArgType >
void Create (ArgType arg, void(*function)(ArgType arg), const char *name, size_t stack_depth, Thread::Priority priority)
 创建新线程 Creates a new thread
 
ErrorCode Join ()
 Waits for this POSIX thread to terminate and releases its resources.
 
 operator libxr_thread_handle ()
 线程对象转换为 POSIX 线程句柄 Converts the thread object to a POSIX thread handle
 

Static Public Member Functions

static Thread Current (void)
 获取当前线程对象 Gets the current thread object
 
static uint32_t GetTime ()
 获取当前系统时间(毫秒) Gets the current system time in milliseconds
 
static void Sleep (uint32_t milliseconds)
 让线程进入休眠状态 Puts the thread to sleep
 
static void SleepUntil (MillisecondTimestamp &last_wakeup_time, uint32_t time_to_sleep)
 让线程休眠直到指定时间点 Puts the thread to sleep until a specified time
 
static void Yield ()
 让出 CPU 以执行其他线程 Yields CPU execution to allow other threads to run
 

Detailed Description

线程管理类,封装 POSIX 线程创建和调度 Thread management class encapsulating POSIX thread creation and scheduling

Definition at line 18 of file thread.hpp.

Member Enumeration Documentation

◆ Priority

enum class LibXR::Thread::Priority : uint8_t
strong

线程优先级枚举 Enumeration for thread priorities

Enumerator
IDLE 

空闲优先级 / Idle priority

LOW 

低优先级 / Low priority

MEDIUM 

中等优先级 / Medium priority

HIGH 

高优先级 / High priority

REALTIME 

实时优先级 / Realtime priority

NUMBER 

优先级数量 / Number of priority levels

Definition at line 25 of file thread.hpp.

26 {
27 IDLE,
28 LOW,
29 MEDIUM,
30 HIGH,
31 REALTIME,
32 NUMBER,
33 };
@ NUMBER
优先级数量 / Number of priority levels
@ LOW
低优先级 / Low priority
@ REALTIME
实时优先级 / Realtime priority
@ IDLE
空闲优先级 / Idle priority
@ HIGH
高优先级 / High priority
@ MEDIUM
中等优先级 / Medium priority

Constructor & Destructor Documentation

◆ Thread() [1/2]

LibXR::Thread::Thread ( )
inline

默认构造函数,初始化空线程 Default constructor initializing an empty thread

Definition at line 39 of file thread.hpp.

39{};

◆ Thread() [2/2]

LibXR::Thread::Thread ( libxr_thread_handle handle)
inline

通过 POSIX 线程句柄创建线程对象 Constructor to create a thread object from a POSIX thread handle

Parameters
handlePOSIX 线程句柄 / POSIX thread handle

Definition at line 46 of file thread.hpp.

46: thread_handle_(handle) {};

Member Function Documentation

◆ Create()

template<typename ArgType >
void LibXR::Thread::Create ( ArgType arg,
void(* function )(ArgType arg),
const char * name,
size_t stack_depth,
Thread::Priority priority )
inline

创建新线程 Creates a new thread

Template Parameters
ArgType线程函数的参数类型 / The type of argument for the thread function
Parameters
arg线程函数的参数 / Argument for the thread function
function线程执行的函数 / Function executed by the thread
name线程名称 / Thread name
stack_depth线程栈大小(字节) / Stack size of the thread (bytes)
priority线程优先级 / Thread priority

该方法基于 POSIX pthread_create() 创建新线程,执行 function 并传递 arg 作为参数。栈大小取 stack_depth 与 PTHREAD_STACK_MIN 中的较大值。SCHED_FIFO 的优先级范围足够时,线程使用 SCHED_FIFO 策略,优先级为最低优先级加 priority; 范围不足或设置优先级失败时使用默认调度策略。 按这些属性创建失败时,改用默认属性重试一次;进程内第一次重试时输出一条警告。

This method creates a new thread using POSIX pthread_create(), executing function with arg as the argument. The stack size is the larger of stack_depth and PTHREAD_STACK_MIN. When the SCHED_FIFO priority range is large enough, the thread uses SCHED_FIFO with the minimum priority plus priority; otherwise, or when setting the priority fails, it uses the default policy. If creation with these attributes fails, it is retried once with default attributes; the first such retry in the process logs a warning.

Definition at line 74 of file thread.hpp.

76 {
77 pthread_attr_t attr;
78 pthread_attr_init(&attr);
79 ConfigureAttributes(attr, stack_depth, priority);
80
81 // 线程数据封装类 / Thread data encapsulation class
82 class ThreadBlock
83 {
84 public:
85 // 存储线程函数、参数和名称 / Store the thread function, argument and name
86 ThreadBlock(decltype(function) fun, ArgType arg, const char* name)
87 : fun_(fun), arg_(arg)
88 {
89 std::memset(name_, 0, sizeof(name_));
90 if (name != nullptr)
91 {
92 std::strncpy(name_, name, sizeof(name_) - 1);
93 }
94 }
95
96 // 线程入口:执行用户函数后释放 ThreadBlock,返回 nullptr / Thread entry: runs the
97 // user function, frees the ThreadBlock and returns nullptr
98 static void* Port(void* arg)
99 {
100 ThreadBlock* block = static_cast<ThreadBlock*>(arg);
101
102 if (block->name_[0] != '\0')
103 {
104 pthread_setname_np(pthread_self(), block->name_);
105 }
106
107 block->fun_(block->arg_);
108 delete block;
109 return static_cast<void*>(nullptr);
110 }
111
112 decltype(function) fun_; // 线程执行的函数 / Function executed by the thread
113 ArgType arg_; // 线程函数的参数 / Argument passed to the thread function
114 char name_[16]; // 线程名称 / Thread name
115 };
116
117 auto block = new ThreadBlock(function, arg, name);
118
119 // 创建线程
120 int ans = pthread_create(&this->thread_handle_, &attr, ThreadBlock::Port, block);
121
122 if (ans != 0)
123 {
124 if (FirstDefaultAttributeRetry())
125 {
126 XR_LOG_WARN(
127 "Failed to create thread: %s (%s), retrying with default attributes. Later "
128 "threads that fail the same way retry without this warning.",
129 name, strerror(ans));
130 }
131
132 // 完全使用系统默认属性(attr = nullptr)
133 ans = pthread_create(&this->thread_handle_, nullptr, ThreadBlock::Port, block);
134
135 if (ans != 0)
136 {
137 XR_LOG_ERROR("Failed to create thread: %s (%s)", name, strerror(ans));
138 delete block;
139 }
140 }
141
142 pthread_attr_destroy(&attr);
143 }

◆ Current()

Thread Thread::Current ( void )
static

获取当前线程对象 Gets the current thread object

Returns
当前线程对象 / The current thread object

Definition at line 13 of file thread.cpp.

13{ return Thread(pthread_self()); }
Thread()
默认构造函数,初始化空线程 Default constructor initializing an empty thread
Definition thread.hpp:39

◆ GetTime()

uint32_t Thread::GetTime ( )
static

获取当前系统时间(毫秒) Gets the current system time in milliseconds

Returns
当前时间(毫秒) / Current time in milliseconds

Definition at line 35 of file thread.cpp.

35{ return Timebase::GetMilliseconds(); }
static MillisecondTimestamp GetMilliseconds()
获取当前时间的毫秒级时间戳。 Gets the current timestamp in milliseconds.

◆ Join()

ErrorCode Thread::Join ( )

Waits for this POSIX thread to terminate and releases its resources.

Returns
OK on success, otherwise FAILED.

Definition at line 39 of file thread.cpp.

40{
41 return pthread_join(thread_handle_, nullptr) == 0 ? ErrorCode::OK : ErrorCode::FAILED;
42}
@ FAILED
操作失败 / Operation failed
@ OK
操作成功 / Operation successful

◆ operator libxr_thread_handle()

LibXR::Thread::operator libxr_thread_handle ( )
inline

线程对象转换为 POSIX 线程句柄 Converts the thread object to a POSIX thread handle

Returns
POSIX 线程句柄 / POSIX thread handle

Definition at line 191 of file thread.hpp.

191{ return thread_handle_; }

◆ Sleep()

void Thread::Sleep ( uint32_t milliseconds)
static

让线程进入休眠状态 Puts the thread to sleep

Parameters
milliseconds休眠时间(毫秒) / Sleep duration in milliseconds

Definition at line 15 of file thread.cpp.

16{
17 timespec ts = MonotonicTime::RelativeFromMilliseconds(milliseconds);
18 while (clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts) == EINTR)
19 {
20 }
21}

◆ SleepUntil()

void Thread::SleepUntil ( MillisecondTimestamp & last_wakeup_time,
uint32_t time_to_sleep )
static

让线程休眠直到指定时间点 Puts the thread to sleep until a specified time

Parameters
last_wakeup_time上次唤醒时间 / Last wake-up time
time_to_sleep休眠时长(毫秒) / Sleep duration in milliseconds

Definition at line 23 of file thread.cpp.

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}

◆ Yield()

void Thread::Yield ( )
static

让出 CPU 以执行其他线程 Yields CPU execution to allow other threads to run

Definition at line 37 of file thread.cpp.

37{ sched_yield(); }

The documentation for this class was generated from the following files: