-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadpool.cc
52 lines (46 loc) · 1.02 KB
/
Threadpool.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//
// Created by 28108 on 2022/11/24.
//
#include "TaskQueue.hpp"
#include "Threadpool.h"
void ThreadPool::init() {
for(int i=0;i<work_threads.size();++i)
{
work_threads[i]=thread(Work(this,i));
}
}
ThreadPool::~ThreadPool() {
shutdown();
}
void ThreadPool::shutdown() {
m_shutdown=true;
cond.notify_all();
for(auto & work_thread : work_threads)
{
if(work_thread.joinable())
{
work_thread.join();
}
}
}
void ThreadPool::Work::operator()() {
std::function<void()>task;
bool dequeued;
while(!m_pool->m_shutdown)
{
{
std::unique_lock<std::mutex>locker(m_pool->m_mutex);
if(m_pool->tasks.empty())
{
std::cout<<m_id<<" is blocked"<<std::endl;
m_pool->cond.wait(locker);
}
std::cout<<"be waked id is "<<m_id<<std::endl;
dequeued=m_pool->tasks.pop(task);
}
if(dequeued)
{
task();
}
}
}