图片引用于百度
简介:线程池模式是指创建多个线程来执行多个任务,这些任务通常组织在一个队列中。正在执行的任务的结果也可能放在队列中,或者任务可能没有返回任何结果。通常,任务比线程多。一旦一个线程完成了它的任务,它就会从队列中请求下一个任务,直到所有任务都完成为止。然后线程可以终止或休眠,直到有新任务可用。
优点:降低消耗资源、提高响应速度和线程管理性
缺点:由于管理着一定数量的线程并时刻等待任务,会占据一定的资源。
例子背景:实现线程池打印全局变量
线程池模式代码:
- 头文件:
#pragma once
#include <thread>
#include <queue>
#include <functional>
#include <vector>
#include <mutex>
#include <condition_variable>
using namespace std;
#define THREADPOOL_MAX_THREAD 10
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
ThreadPool(ThreadPool&) = delete;
ThreadPool& operator=(ThreadPool&) = delete;
public:
typedef function<void(void)> fnTask;
private:
queue<fnTask> m_queueTask;
vector<thread*> m_thArr;
condition_variable m_cond;
mutex m_mutex;
bool m_isStart;
private:
fnTask take();
void threadLoop();
public:
void AddTask(const fnTask& tsk);
void StartThreadPool();
void StopThreadPool();
};
- 实现:
#include "ThreadPool.h"
ThreadPool::ThreadPool() : m_isStart(false)
{
}
ThreadPool::~ThreadPool()
{
for (int i = 0; i < m_thArr.size(); ++i)
{
delete m_thArr.at(i);
}
}
ThreadPool::fnTask ThreadPool::take()
{
unique_lock<mutex> lck(m_mutex);
if (m_queueTask.empty() && m_isStart)
{
m_cond.wait(lck);
}
fnTask fntask;
if (!m_queueTask.empty() && m_isStart)
{
fntask = m_queueTask.front();
m_queueTask.pop();
}
return fntask;
}
void ThreadPool::threadLoop()
{
while (m_isStart)
{
fnTask task = take();
if (task)
{
task();
}
}
}
void ThreadPool::AddTask(const fnTask& tsk)
{
unique_lock<mutex> lck(m_mutex);
m_queueTask.push(tsk);
m_cond.notify_all();
}
void ThreadPool::StartThreadPool()
{
m_isStart = true;
_ASSERT(m_thArr.empty());
for (int i = 0; i < THREADPOOL_MAX_THREAD; ++i)
{
m_thArr.push_back(new thread(bind(&ThreadPool::threadLoop, this)));
}
}
void ThreadPool::StopThreadPool()
{
unique_lock<std::mutex> lock(m_mutex);
m_isStart = false;
m_cond.notify_all();
}
- 引用:
#include "ThreadPool.h"
#include <stdio.h>
#include <windows.h>
int i = 1;
int main()
{
ThreadPool::fnTask th = [=]{ printf("%d\n", i++); };
ThreadPool tp;
for (int i = 0; i < 20; ++i)
{
tp.AddTask(th);
}
tp.StartThreadPool();
Sleep(2000);
for (int i = 0; i < 15; ++i)
{
tp.AddTask(th);
}
Sleep(1000);
for (int i = 0; i < 8; ++i)
{
tp.AddTask(th);
}
tp.StopThreadPool();
getchar();
return 0;
}
总结:
线程池模式(Thread Pool):线程池模式通过管理一定数量的线程,降低了多线程的创建线程和销毁线程开销并提高了线程对执行任务的响应速度
作者:丶梦爱
博客:https://blog.youkuaiyun.com/u014732297(转载请说明出处)