当前位置:网站首页>Don't you understand the design and principle of thread pool? Break it up and crush it. I'll teach you how to design the thread pool
Don't you understand the design and principle of thread pool? Break it up and crush it. I'll teach you how to design the thread pool
2022-06-11 15:13:00 【InfoQ】
Thread pool design ideas
What is a thread pool

Why do I need thread pools
How to design thread pool

【 Article Welfare 】 In addition, Xiaobian also sorted out some C++ Back-end development interview questions , Teaching video , Back end learning roadmap for free , You can add what you need :
Click to join the learning exchange group ~
Group file sharing
Xiaobian strongly recommends C++ Back end development free learning address :
C/C++Linux Server development senior architect /C++ Background development architect

Design thinking
- We need to store the threads we created , So we need a container for threads
- We need a container to store our tasks , Put the task in this container every time
- Because it is a multithreaded read task , So it's essential that we need a lock , Each read task requires locking and unlocking
- We need to judge when to terminate , Therefore, we also need a variable to judge the termination
- In order to avoid polling to determine whether the task container is empty , It's too inefficient , So we use conditional variables here
- The operation of adding a task to the thread pool , And at this time, it should inform the thread that it can pick up the task to execute
- A loop operation , Constantly waiting for data in the task container to execute , That is, what needs to be done after initialization
- Stop the above loop by changing the termination variable
Implementation of thread pool
class CThreadMangerPool
{
public:
CThreadMangerPool(void):is_runing(false){};
bool init(int threadnum);// Initialization function
~CThreadMangerPool(void);
void Run(void); // Execute function
void stop(void); // The function used to terminate the loop
void addTask(ThreadTask* task);// Add the function of the task to the task container
private:
bool CreateThreads(int threadnum = 5);
std::vector<std::shared_ptr<std::thread>> threadsPool; // Thread container , To hold threads
std::list<std::shared_ptr<ThreadTask>> threadTaskList; // Task container , Used to store tasks executed by threads
std::condition_variable threadPool_cv; // Condition variables,
std::mutex threadMutex; // The mutex
//std::vector<std::shared_ptr<CTcpClient>> tcpClients;
bool is_runing; // Terminate variable
};void CThreadMangerPool::Run(){
std::shared_ptr<ThreadTask> task;
while(true){ // In circulation
std::unique_lock<std::mutex> guard(threadMutex);// utilize RALL To manage locks , No manual release
while(threadTaskList.empty()){ // False awakening of condition variables is prevented here , So there's no need to if Judge
if (!is_runing)
break;
threadPool_cv.wait(guard); // The use of conditional variables
}
if (!is_runing) // ditto It is to judge if it is not started or if stop Functions exit the loop
break;
task = threadTaskList.front(); // Take out the task
threadTaskList.pop_front(); // Take the task out of the container
if (task == NULL)
continue;
task->DoIt(); // Execute task handling functions
task.reset(); // Reset pointer
}
}void CThreadMangerPool::addTask(ThreadTask* task){
std::shared_ptr<ThreadTask> ptr; // Create a smart pointer to the task
ptr.reset(task);
{
std::lock_guard<std::mutex> guard(threadMutex); // It's also used RALL To manage locks , No manual release
threadTaskList.push_back(ptr); // Add a task... To the task container
}
threadPool_cv.notify_all(); // The notification thread is ready to execute , Is the condition that wakes up just sleeping at the condition variable
}Reference material
边栏推荐
- 19. insertion, deletion and pruning of binary search tree
- Qualcomm WLAN framework learning (29) -- 6GHz overview
- 2022 simulated 100 questions and simulated examination of quality officer municipal direction post skills (Quality Officer) examination
- Nexus of repository manager
- 以 Log4j 为例,如何评估和划分安全风险
- Leetcode daily question - Search insertion position
- When open source meets KPI, globalization vs localization, how can the ideal and reality of open source be reconciled?
- Hebei huangjinzhai scenic spot adds "AED automatic defibrillator" to ensure the life safety of tourists!
- System. out. What should I pay attention to when using the println () method
- Backtracking / activity scheduling maximum compatible activities
猜你喜欢

19. 二叉搜索樹的插入删除修剪
![[SystemVerilog interface] ~ interface](/img/dc/0a9750cace1460af772e2f3f6a8763.png)
[SystemVerilog interface] ~ interface

数据库优化
![[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator](/img/3a/0cc26400eeb4b388face09b9a10f27.png)
[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator

腾讯面试官分享面试经验,如何考察面试者技术及个人综合素质,给正在面试的你一点建议

See from the minute, carve on the details: Exploration of SVG generated vector format website icon (favicon)

数据分析系统的设计与实现

What is excess product power? Find the secret key of the second generation cs75plus in the year of the tiger

LoveLive! Published an AI paper: generating models to write music scores automatically

uniapp开发微信小程序,从构建到上线
随机推荐
Flutter 3.0正式发布:稳定支持6大平台,字节跳动是主要用户
当开源遇见 KPI,全球化 VS 本土化,开源的理想与现实该如何和解?
简单的C语言版本通讯录
Hebei huangjinzhai scenic spot adds "AED automatic defibrillator" to ensure the life safety of tourists!
02 Tekton Pipeline
Exporting data using mysqldump
Flutter 3.0 was officially released: it stably supports 6 platforms, and byte jitter is the main user
Explain the kubernetes package management tool Helm
中国技术出海,TiDB 数据库海外探索之路 | 卓越技术团队访谈录
Database optimization
百度某离职员工跳槽字节被判赔107万元;苹果谷歌微软拟“干掉”密码;传吉利已收购魅族|Q资讯
Taking log4j as an example, how to evaluate and classify security risks
19. insertion, deletion and pruning of binary search tree
Flower shop window (linear DP)
A former employee of Baidu was awarded 1.07 million yuan for job hopping; Apple, Google and Microsoft plan to "kill" the password; It is said that Geely has acquired Meizu | Q information
Simple C language address book
What is excess product power? Find the secret key of the second generation cs75plus in the year of the tiger
safePoint讲解及其安插思路分析
Hamad application layout scheme 02 of hashicopy
2022质量员-市政方向-岗位技能(质量员)考试模拟100题及模拟考试