brpc源码解析之bthread_start_background函数

bthread_start_background 函数在后端创建一个bthread,但是该bthread没有立刻运行,而是等待空闲的worker pthread将其偷过来运行,函数行为类似于 pthread_create。其函数声明为:

// Create bthread `fn(args)' with attributes `attr' and put the identifier into
// `tid'. This function behaves closer to pthread_create: after scheduling the
// new thread to run, it returns. In another word, the new thread may take
// longer time than bthread_start_urgent() to run.
// Return 0 on success, errno otherwise.
extern int bthread_start_background(bthread_t* __restrict tid,
                                    const bthread_attr_t* __restrict attr,
                                    void * (*fn)(void*),
                                    void* __restrict args);

根据当前pthread是不是worker pthread采取不同的做法:

  • 如果我们是在worker pthread中调用该函数,即 bthread::tls_task_group 不为NULL,新的bthread会加入到本地队列中等待调度。
  • 否则,随机选择一个TaskGroup,将新的bthread加入到其远程队列中。
  • 调用 TaskControl::signal_task 唤醒休眠的worker pthread,运行新的bthread。

这里要注意,创建bthread,就是为新的bthread分配控制结构以及tid。创建bthread时没有立刻为其分配栈,直到第一次运行时才会分配。这个便于我们优化内存的使用,如果前一个bthread即将退出并且栈类型和下一个bhtread相同,我们可以直接转移栈而不需要重新分配。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容