- Thread
Thread 中包括完整的
- 消息队列
- 线程创建同步
- 消息回调处理
thread 的实现依赖如下模块:
- reactor -> 利用epoll实现的消息收发机制
- semaphore -> 线程创建同步
- fixed_queue -> 消息队列(也利用semaphone 进行同步)
Thread 的创建过程:
thread_t* thread_new_sized(const char* name, size_t work_queue_capacity) {
CHECK(name != NULL);
CHECK(work_queue_capacity != 0);
thread_t* ret = static_cast<thread_t*>(osi_calloc(sizeof(thread_t)));
ret->reactor = reactor_new(); 创建reactor
if (!ret->reactor) goto error;
ret->work_queue = fixed_queue_new(work_queue_capacity); 创建fixed_queue
if (!ret->work_queue) goto error;
// Start is on the stack, but we use a semaphore, so it's safe
struct start_arg start;
start.start_sem = semaphore_new(0); start_sem是用来做线程启动同步的
if (!start.start_sem) goto error;
strncpy(ret->name, name, THREAD_NAME_MAX);
start.thread = ret;
start.error = 0;
pthread_create(&ret->pthread, NULL, run_thread, &start);
semaphore_wait(start.start_sem); start_sem 此处一直在等待,释放semophore 是在run_thread 中完成的,此semphore 可以保证线程启动完成这个函数才会推出,另一层含义就是这个函数的执行是需要时间的
semaphore_free(start.start_sem); start_sem 完成使命,被释放掉
if (start.error) goto error;
return ret;
error:;
if (ret) {
fixed_queue_free(ret->work_queue, osi_free);
reactor_free(ret->reactor);
}
osi_free(ret);
return NULL;
}
Thread 执行函数
static void* run_thread(void* start_arg) {
CHECK(start_arg != NULL);
struct start_arg* start = static_cast<struct start_arg*>(start_arg);
thread_t* thread = start->thread;
CHECK(thread != NULL);
if (prctl(PR_SET_NAME, (unsigned long)thread->name) == -1) { 设置线程名称
LOG_ERROR(LOG_TAG, "%s unable to set thread name: %s", __func__,
strerror(errno));
start->error = errno;
semaphore_post(start->start_sem); 释放start_sem
return NULL;
}
thread->tid = gettid(); 获取线程ID
LOG_INFO(LOG_TAG, "%s: thread id %d, thread name %s started", __func__,
thread->tid, thread->name);
semaphore_post(start->start_sem); 释放start_sem
int fd = fixed_queue_get_dequeue_fd(thread->work_queue);
void* context = thread->work_queue; contex, work_queue_read_cb 作为事件处理的上下文和回调函数
reactor_object_t* work_queue_object =
reactor_register(thread->reactor, fd, context, work_queue_read_cb, NULL);
reactor_start(thread->reactor); 线程执行内容
reactor_unregister(work_queue_object); 线程执行完成,准备退出
// Make sure we dispatch all queued work items before exiting the thread.
// This allows a caller to safely tear down by enqueuing a teardown
// work item and then joining the thread.
size_t count = 0;
work_item_t* item =
static_cast<work_item_t*>(fixed_queue_try_dequeue(thread->work_queue));
while (item && count <= fixed_queue_capacity(thread->work_queue)) {
item->func(item->context);
osi_free(item);
item =
static_cast<work_item_t*>(fixed_queue_try_dequeue(thread->work_queue));
++count;
}
if (count > fixed_queue_capacity(thread->work_queue))
LOG_DEBUG(LOG_TAG, "%s growing event queue on shutdown.", __func__);
LOG_WARN(LOG_TAG, "%s: thread id %d, thread name %s exited", __func__,
thread->tid, thread->name);
return NULL;
}
从上面的代码初看似乎代码并未一直在执行(通常我们创建thread 中会有个while(1)) ,其实是在reactor start 中完成的
在线程退出时遍历quene,使所有的消息得到执行