最近面试被问到c++11的一些特性,有点模糊了,撸个c++11实现的简易线程池玩玩,强化一下记忆。
目录
threadManage.h
#pragma once
#include <thread>
#include <vector>
#include <queue>
#include <condition_variable>
#include <mutex>
#include <iostream>
using namespace std;
class ThreadManage
{
typedef std::function < void() > Task;
public:
ThreadManage(int num);
~ThreadManage();
public:
void StartThread();
void StopThread();
void AddTask(Task task);
private:
void Work();
private:
std::vector<std::thread*> m_threads;
std::queue<Task> m_task;
std::mutex m_mutex;
std::condition_variable m_condtion;
volatile bool m_bIsBusy;
int m_ThreadNum;
};
threadManage.cpp
#include "threadManage.h"
ThreadManage::ThreadManage(int num) :m_ThreadNum(num), m_bIsBusy(false)
{
}
ThreadManage::~ThreadManage()
{
if (m_bIsBusy)
StopThread();
}
void ThreadManage::StartThread()
{
m_bIsBusy = true;
for (int i = 0; i < m_ThreadNum; i++)
{
m_threads.push_back(new std::thread(std::bind(&ThreadManage::Work, this)));
//std::unique_lock<std::mutex> lock(m_mutex);
//chrono::microseconds time(1000);
//m_condtion.wait_for(lock, time);
}
}
void ThreadManage::StopThread()
{
{
std::unique_lock<std::mutex> lock(m_mutex);
m_bIsBusy = false;
}
if (!m_threads.empty())
m_condtion.notify_all();
for (auto& thread : m_threads)
{
if (thread->joinable())
{
cout << thread->get_id() << endl;
thread->join();
delete thread;
}
}
m_threads.clear();
}
void ThreadManage::AddTask(Task task)
{
if (m_bIsBusy)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_task.push(task);
m_condtion.notify_one();
}
}
void ThreadManage::Work()
{
while (m_bIsBusy)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_condtion.wait(lock);
if (m_task.empty()) continue;
else
{
Task task;
task = m_task.front();
m_task.pop();
task();
}
}
}
main.cpp
#include "threadManage.h"
void func()
{
cout << "func" << endl;
}
int main()
{
cout << "main" << endl;
//thread th(func);
//th.join();
ThreadManage thread(3);
thread.StartThread();
for (int i = 0; i < 3; i++)
{
thread.AddTask(func);
}
std::this_thread::sleep_for(std::chrono::microseconds(1000));
thread.StopThread();
return 0;
}