mirror of
https://gitee.com/fasiondog/hikyuu.git
synced 2024-12-01 03:18:18 +08:00
优化线程池
This commit is contained in:
parent
1b2ea289bb
commit
ff43b318cd
@ -80,6 +80,7 @@ public:
|
||||
} else {
|
||||
m_master_work_queue.push(std::move(task));
|
||||
}
|
||||
m_cv.notify_one();
|
||||
return res;
|
||||
}
|
||||
|
||||
@ -88,6 +89,7 @@ public:
|
||||
*/
|
||||
void stop() {
|
||||
m_done = true;
|
||||
m_cv.notify_all(); // 唤醒所有工作线程
|
||||
for (size_t i = 0; i < m_worker_num; i++) {
|
||||
if (m_threads[i].joinable()) {
|
||||
m_threads[i].join();
|
||||
@ -105,6 +107,9 @@ public:
|
||||
m_master_work_queue.push(std::move(FuncWrapper()));
|
||||
}
|
||||
|
||||
// 唤醒所有工作线程
|
||||
m_cv.notify_all();
|
||||
|
||||
// 等待线程结束
|
||||
for (size_t i = 0; i < m_worker_num; i++) {
|
||||
if (m_threads[i].joinable()) {
|
||||
@ -120,6 +125,8 @@ private:
|
||||
std::atomic_bool m_done; // 线程池全局需终止指示
|
||||
bool m_init_finished; // 线程池是否初始化完毕
|
||||
size_t m_worker_num; // 工作线程数量
|
||||
std::condition_variable m_cv; // 信号量,无任务时阻塞线程并等待
|
||||
std::mutex m_cv_mutex; // 配合信号量的互斥量
|
||||
|
||||
ThreadSafeQueue<task_type> m_master_work_queue; // 主线程任务队列
|
||||
std::vector<std::unique_ptr<WorkStealQueue> > m_queues; // 任务队列(每个工作线程一个)
|
||||
@ -145,16 +152,21 @@ private:
|
||||
task_type task;
|
||||
if (pop_task_from_local_queue(task)) {
|
||||
task();
|
||||
std::this_thread::yield();
|
||||
} else if (pop_task_from_master_queue(task)) {
|
||||
if (!task.isNullTask()) {
|
||||
task();
|
||||
std::this_thread::yield();
|
||||
} else {
|
||||
m_thread_need_stop = true;
|
||||
}
|
||||
} else if (pop_task_from_other_thread_queue(task)) {
|
||||
task();
|
||||
} else {
|
||||
std::this_thread::yield();
|
||||
} else {
|
||||
// std::this_thread::yield();
|
||||
std::unique_lock<std::mutex> lk(m_cv_mutex);
|
||||
m_cv.wait(lk);
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user