| 45 | |
| 46 | |
| 47 | CStatus UThreadPool::init() { |
| 48 | CGRAPH_FUNCTION_BEGIN |
| 49 | if (is_init_) { |
| 50 | CGRAPH_FUNCTION_END |
| 51 | } |
| 52 | |
| 53 | if (config_.monitor_enable_) { |
| 54 | // 默认不开启监控线程 |
| 55 | monitor_thread_ = std::thread(&UThreadPool::monitor, this); |
| 56 | } |
| 57 | thread_record_map_.clear(); |
| 58 | thread_record_map_[std::hash<std::thread::id>{}(std::this_thread::get_id())] = CGRAPH_MAIN_THREAD_ID; |
| 59 | task_queue_.setup(); |
| 60 | primary_threads_.reserve(config_.default_thread_size_); |
| 61 | for (int i = 0; i < config_.default_thread_size_; i++) { |
| 62 | auto* pt = CGRAPH_SAFE_MALLOC_COBJECT(UThreadPrimary); // 创建核心线程数 |
| 63 | pt->setThreadPoolInfo(i, &task_queue_, &primary_threads_, &config_); |
| 64 | // 记录线程和匹配id信息 |
| 65 | primary_threads_.emplace_back(pt); |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * 等待所有thread 设置完毕之后,再进行 init(), |
| 70 | * 避免在个别的平台上,可能出现 thread竞争访问其他线程、并且导致异常的情况 |
| 71 | * 参考: https://github.com/ChunelFeng/CGraph/issues/309 |
| 72 | */ |
| 73 | for (int i = 0; i < config_.default_thread_size_; i++) { |
| 74 | status += primary_threads_[i]->init(); |
| 75 | thread_record_map_[std::hash<std::thread::id>{}(primary_threads_[i]->thread_.get_id())] = i; |
| 76 | } |
| 77 | CGRAPH_FUNCTION_CHECK_STATUS |
| 78 | |
| 79 | /** |
| 80 | * 策略更新: |
| 81 | * 初始化的时候,也可以创建n个辅助线程。目的是为了配合仅使用 pool中 priority_queue 的场景 |
| 82 | * 一般情况下,建议为0。 |
| 83 | */ |
| 84 | status = createSecondaryThread(config_.secondary_thread_size_); |
| 85 | CGRAPH_FUNCTION_CHECK_STATUS |
| 86 | |
| 87 | is_init_ = true; |
| 88 | CGRAPH_FUNCTION_END |
| 89 | } |
| 90 | |
| 91 | |
| 92 | CStatus UThreadPool::submit(const UTaskGroup& taskGroup, const CMSec ttl) { |
no test coverage detected