线程工作队列 (thworker)
基于后台线程的异步任务执行器,内部维护任务队列,通过信号量唤醒工作线程逐个执行提交的任务,适用于将耗时操作卸载到后台线程的场景。
数据结构
struct thworker_t {
struct list_head_t head; /* 任务队列 */
struct mutex_t lock; /* 互斥锁,保护任务队列 */
struct semaphore_t sem; /* 信号量,通知工作线程有新任务 */
struct thread_t * thread; /* 后台工作线程 */
int running; /* 运行标志,1 表示运行中 */
};
任务结构
struct thworker_task_t {
struct list_head_t entry; /* 链表节点 */
void (*func)(void *); /* 任务函数 */
void * data; /* 用户数据 */
};
工作原理
工作线程循环
工作线程在 thworker_alloc() 时创建,循环执行以下逻辑: