libxr  1.0
Want to be the best embedded framework
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
 
 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 (TimestampMS &last_waskup_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
 

Private Attributes

libxr_thread_handle thread_handle_
 POSIX 线程句柄 POSIX thread handle.
 

Detailed Description

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

Definition at line 13 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 20 of file thread.hpp.

21 {
22 IDLE,
23 LOW,
24 MEDIUM,
25 HIGH,
26 REALTIME,
27 NUMBER,
28 };
@ 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 34 of file thread.hpp.

34{};

◆ 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 41 of file thread.hpp.

41: thread_handle_(handle) {};
libxr_thread_handle thread_handle_
POSIX 线程句柄 POSIX thread handle.
Definition thread.hpp:219

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 需要进行调整以符合 POSIX 线程的栈管理方式。 如果系统支持 SCHED_RR 调度策略,则设置线程优先级。

This method creates a new thread using POSIX pthread_create(), executing function with arg as the argument. The stack_depth needs adjustment for POSIX thread stack management. If the system supports SCHED_RR scheduling, thread priority is set accordingly.

线程数据封装类 Thread data encapsulation class

构造函数,存储线程相关数据 Constructor to store thread-related data

Parameters
fun线程执行的函数 Function executed by the thread
arg线程参数 Thread argument
name线程名称 Thread name

线程入口函数,执行用户定义的线程函数 Thread entry function that executes the user-defined function

Parameters
arg线程参数 Thread argument
Returns
返回值始终为 nullptr The return value is always nullptr

< 线程执行的函数 Function executed by the thread

< 线程函数的参数 Argument passed to the thread function

< 线程名称 Thread name

Definition at line 64 of file thread.hpp.

66 {
67 pthread_attr_t attr;
68 pthread_attr_init(&attr);
69
70 // 线程栈大小设定,至少满足 PTHREAD_STACK_MIN
71 size_t stack_size = LibXR::max(static_cast<size_t>(PTHREAD_STACK_MIN), stack_depth);
72 pthread_attr_setstacksize(&attr, stack_size);
73
78 class ThreadBlock
79 {
80 public:
88 ThreadBlock(decltype(function) fun, ArgType arg, const char *name)
89 : fun_(fun),
90 arg_(arg),
91 name_(reinterpret_cast<char *>(malloc(strlen(name) + 1)))
92 {
93 strcpy(name_, name);
94 }
95
96 ~ThreadBlock() { free(name_); }
97
105 static void *Port(void *arg)
106 {
107 ThreadBlock *block = static_cast<ThreadBlock *>(arg);
108 volatile const char *thread_name = block->name_;
109 block->fun_(block->arg_);
110
111 UNUSED(thread_name);
112 delete block;
113 return static_cast<void *>(nullptr);
114 }
115
116 decltype(function) fun_;
117 ArgType arg_;
118 char *name_;
119 };
120
121 auto block = new ThreadBlock(function, arg, name);
122
123 // 优先尝试设置 SCHED_FIFO 和线程优先级
124 int min_priority = sched_get_priority_min(SCHED_FIFO);
125 int max_priority = sched_get_priority_max(SCHED_FIFO);
126 bool scheduling_set = false;
127
128 UNUSED(scheduling_set);
129
130 if (max_priority - min_priority >= static_cast<int>(Priority::REALTIME))
131 {
132 pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
133 pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
134
135 struct sched_param sp;
136 memset(&sp, 0, sizeof(sp));
137 sp.sched_priority = min_priority + static_cast<int>(priority);
138
139 if (pthread_attr_setschedparam(&attr, &sp) == 0)
140 {
141 scheduling_set = true;
142 }
143 else
144 {
145 XR_LOG_WARN("Failed to set thread priority. Falling back to default policy.");
146 pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
147 pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
148 }
149 }
150 else
151 {
152 XR_LOG_WARN(
153 "SCHED_FIFO not supported or insufficient range. Using default policy.");
154 pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
155 }
156
157 // 创建线程
158 int ans = pthread_create(&this->thread_handle_, &attr, block->Port, block);
159 if (ans != 0)
160 {
161 XR_LOG_WARN("Failed to create thread: %s (%s), Falling back to default policy.",
162 name, strerror(ans));
163 pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
164 pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
165 ans = pthread_create(&this->thread_handle_, &attr, block->Port, block);
166 if (ans != 0)
167 {
168 XR_LOG_ERROR("Failed to create thread: %s (%s)", name, strerror(ans));
169 delete block;
170 }
171 }
172
173 pthread_attr_destroy(&attr);
174 }
constexpr auto max(T1 a, T2 b) -> typename std::common_type< T1, T2 >::type
计算两个数的最大值

◆ Current()

Thread Thread::Current ( void )
static

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

Returns
当前线程对象 The current thread object

Definition at line 14 of file thread.cpp.

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

◆ GetTime()

uint32_t Thread::GetTime ( )
static

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

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

Definition at line 39 of file thread.cpp.

39 {
40 struct timeval tv;
41 gettimeofday(&tv, nullptr);
42 return ((tv.tv_sec - libxr_linux_start_time.tv_sec) * 1000 +
43 (tv.tv_usec - libxr_linux_start_time.tv_usec) / 1000) %
44 UINT32_MAX;
45}

◆ 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 216 of file thread.hpp.

216{ 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 16 of file thread.cpp.

16 {
17 struct timespec ts;
18 ts.tv_sec = milliseconds / 1000;
19 ts.tv_nsec = static_cast<__syscall_slong_t>((milliseconds % 1000) * 1000000);
20 UNUSED(clock_nanosleep(CLOCK_REALTIME, 0, &ts, nullptr));
21}

◆ SleepUntil()

void Thread::SleepUntil ( TimestampMS & last_waskup_time,
uint32_t time_to_sleep )
static

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

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

Definition at line 23 of file thread.cpp.

23 {
24 last_waskup_time = last_waskup_time + time_to_sleep;
25
26 struct timespec ts = libxr_linux_start_time_spec;
27 uint32_t add = 0;
28 uint32_t secs = last_waskup_time / 1000;
29 int64_t raw_time = static_cast<int64_t>(last_waskup_time) * 1000U * 1000U;
30 add = raw_time / (static_cast<int64_t>(1000U * 1000U * 1000U));
31 ts.tv_sec += (add + secs);
32 ts.tv_nsec = raw_time % (static_cast<int64_t>(1000U * 1000U * 1000U));
33
34 while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &ts, &ts) &&
35 errno == EINTR) {
36 }
37}

◆ Yield()

void Thread::Yield ( )
static

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

Definition at line 47 of file thread.cpp.

47{ sched_yield(); }

Field Documentation

◆ thread_handle_

libxr_thread_handle LibXR::Thread::thread_handle_
private

POSIX 线程句柄 POSIX thread handle.

Definition at line 219 of file thread.hpp.


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