线程池开源项目阅读
# 设置线程名
#include <sys/prctl.h>
//Set the name of the calling thread. The name can be up to 16 bytes long, including the terminating null byte.
prctl(PR_SET_NAME, "thread_a");
1
2
3
4
2
3
4
# C-Thread-Pool开源项目阅读
# thread_do()
- thpool_ 结构体中存储了线程指针,jobqueue指针;
- thread_init()函数创建若干线程,并执行thread_do()函数,thread_do()内循环执行,jobqueue_pull(), 从jobqueue中取任务并执行
# bsem结构体
- bsem结构体
typedef struct bsem { pthread_mutex_t mutex; pthread_cond_t cond; int v; } bsem;
1
2
3
4
5 - 可以把它看做bool semaphore,v在使用时只会被赋给0或者1。
- bsem_wait(* bsem) 会使当前线程在cond上挂起等待。
- bsem_post(* bsem) 会唤醒等待在cond上的一个线程。
- jobqueue_p->has_jobs 就是一个bsem结构体,表示当前jobqueue中有没有任务。(不表示任务数量)
# thread_do() 和 jobqueue()
- thread_do()中在执行jobqueue_pull()之前,会执行bsem_wait(jobqueue_p->has_jobs),如果没有任务就挂起等待,有任务时被唤醒,然后把has_jobs置为0
- bsem_wait(has_jobs)等到有任务后执行jobqueue_pull(), 首先上一个mutex锁(jobqueue_p->rwmutex),然后从任务链表中取任务,取完如果还有任务,就会执行bsem_post()再唤醒下一个线程。然后解锁rwmutex。
编辑 (opens new window)
上次更新: 2023/05/07, 17:27:54