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 (MillisecondTimestamp &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 15 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 22 of file thread.hpp.

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

36{};

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

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

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

68 {
69 pthread_attr_t attr;
70 pthread_attr_init(&attr);
71
72 // 线程栈大小设定,至少满足 PTHREAD_STACK_MIN
73 size_t stack_size = LibXR::max(static_cast<size_t>(PTHREAD_STACK_MIN), stack_depth);
74 pthread_attr_setstacksize(&attr, stack_size);
75
80 class ThreadBlock
81 {
82 public:
90 ThreadBlock(decltype(function) fun, ArgType arg, const char *name)
91 : fun_(fun),
92 arg_(arg),
93 name_(reinterpret_cast<char *>(malloc(strlen(name) + 1)))
94 {
95 strcpy(name_, name);
96 }
97
98 ~ThreadBlock() { free(name_); }
99
107 static void *Port(void *arg)
108 {
109 ThreadBlock *block = static_cast<ThreadBlock *>(arg);
110
111 if (block->name_ && block->name_[0] != '\0')
112 {
113 char name_buf[16];
114 std::strncpy(name_buf, block->name_, sizeof(name_buf) - 1);
115 name_buf[sizeof(name_buf) - 1] = '\0';
116 pthread_setname_np(pthread_self(), name_buf);
117 }
118
119 volatile const char *thread_name = block->name_;
120 block->fun_(block->arg_);
121
122 UNUSED(thread_name);
123 delete block;
124 return static_cast<void *>(nullptr);
125 }
126
127 decltype(function) fun_;
128 ArgType arg_;
129 char *name_;
130 };
131
132 auto block = new ThreadBlock(function, arg, name);
133
134 // 优先尝试设置 SCHED_FIFO 和线程优先级
135 int min_priority = sched_get_priority_min(SCHED_FIFO);
136 int max_priority = sched_get_priority_max(SCHED_FIFO);
137 bool scheduling_set = false;
138
139 UNUSED(scheduling_set);
140
141 if (max_priority - min_priority >= static_cast<int>(Priority::REALTIME))
142 {
143 pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
144 pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
145
146 struct sched_param sp;
147 Memory::FastSet(&sp, 0, sizeof(sp));
148 sp.sched_priority = min_priority + static_cast<int>(priority);
149
150 if (pthread_attr_setschedparam(&attr, &sp) == 0)
151 {
152 scheduling_set = true;
153 }
154 else
155 {
156 XR_LOG_WARN("Failed to set thread priority. Falling back to default policy.");
157 pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
158 pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
159 }
160 }
161 else
162 {
163 XR_LOG_WARN(
164 "SCHED_FIFO not supported or insufficient range. Using default policy.");
165 pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
166 }
167
168 // 创建线程
169 int ans = pthread_create(&this->thread_handle_, &attr, ThreadBlock::Port, block);
170
171 pthread_attr_destroy(&attr);
172
173 if (ans != 0)
174 {
175 XR_LOG_WARN("Failed to create thread: %s (%s), retrying with default attributes.",
176 name, strerror(ans));
177
178 // 完全使用系统默认属性(attr = nullptr)
179 ans = pthread_create(&this->thread_handle_, nullptr, ThreadBlock::Port, block);
180
181 if (ans != 0)
182 {
183 XR_LOG_ERROR("Failed to create thread: %s (%s)", name, strerror(ans));
184 delete block;
185 }
186 }
187
188 pthread_attr_destroy(&attr);
189 }
static void FastSet(void *dst, uint8_t value, size_t size)
快速内存填充 / Fast memory fill
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:36

◆ GetTime()

uint32_t Thread::GetTime ( )
static

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

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

Definition at line 41 of file thread.cpp.

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

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

231{ 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.

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

◆ SleepUntil()

void Thread::SleepUntil ( MillisecondTimestamp & 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 24 of file thread.cpp.

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

◆ Yield()

void Thread::Yield ( )
static

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

Definition at line 50 of file thread.cpp.

50{ sched_yield(); }

Field Documentation

◆ thread_handle_

libxr_thread_handle LibXR::Thread::thread_handle_
private

POSIX 线程句柄 POSIX thread handle.

Definition at line 234 of file thread.hpp.


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