c++11 线程池实现

#ifndef THREAD_POOL_H
#define THREAD_POOL_H
ThreadPool.h
#include <thread>
#include <thread>
#include <condition_variable>
#include <functional>
#include <vector>
#include <queue>
using namespace std;
class ThreadPool
{
public:
using Task = std::function<void()>;
explicit ThreadPool(int num): _thread_num(num), _is_running(false) {}
~ThreadPool() {
if (_is_running)
stop();
}
void start() {
_is_running = true;
// start threads
for (int i = 0; i < _thread_num; i++)
_threads.emplace_back(std::thread(&ThreadPool::work, this));
}
void stop()
{
{
// stop thread pool, should notify all threads to wake
std::unique_lock<std::mutex> lk(_mtx);
_is_running = false;
_cond.notify_all(); // must do this to avoid thread block
}
// terminate every thread job
for (auto& t : _threads){
if (t.joinable())
t.join();
}
}
void appendTask(const Task& task)
{
if (_is_running) {
std::unique_lock<std::mutex> lk(_mtx);
_tasks.push(task);
_cond.notify_one(); // wake a thread to to the task
}
}
private:
void work()
{
cout<<“begin work thread: %d\n”, std::this_thread::get_id();
while (_is_running||!_threads.empty())
{
Task task;
{
std::unique_lock<std::mutex>lk(_mtx);
if (!_tasks.empty()) {
task = _tasks.front();
_tasks.pop(); // remove the task
_cond.notify_one();
}
else{
_cond.wait(lk);
}
}
if (task)
task(); // do the task
}
cout<<“end work thread: %d\n”, std::this_thread::get_id();
}
public:
// disable copy and assign construct
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool& other) = delete;
private:
bool _is_running; // thread pool manager status
std::mutex _mtx;
std::condition_variable _cond;
int _thread_num;
std::vector<std::thread>_threads;
std::queue<Task>_tasks;
};
#endif //

main.cpp
#include “ThreadPool.h”
void fun1()
{
std::cout << "working in thread " << std::this_thread::get_id() << std::endl;
}
void fun2(int x)
{
std::cout << "task " << x << " working in thread " << std::this_thread::get_id() << std::endl;
}
int main(int argc, char* argv[])
{
ThreadPool thread_pool(3);
thread_pool.start();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
for (int i = 0; i < 6; i++) {
//thread_pool.appendTask(fun1);
thread_pool.appendTask(std::bind(fun2, i));
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
thread_pool.stop();
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值