#include "stdafx.h"
#include "ThreadPool.h"
ThreadPool::ThreadPool(int thread_num) : stop_(false)
{
for (int count = 0; count < thread_num; count++){
pools_.emplace_back(&work, this);
}
}
ThreadPool::~ThreadPool()
{
stop_.store(true);
c_.notify_all();
for (std::thread& thread : pools_){
thread.join();
}
}
std::shared_ptr<Task> ThreadPool::get_one_task()
{
std::unique_lock<std::mutex> lock(mutex_);
c_.wait(lock, [this](){
return stop_.load() || !task_.empty();
});
if (!task_.empty()){
std::shared_ptr<Task> ptask = std::move(task_.front());
task_.pop();
return ptask;
}
return std::make_shared<Task>();
}
void ThreadPool::work(ThreadPool *pthis)
{
while (!pthis->stop_.load()){
auto task = pthis->get_one_task();
task->run();
}
}
void ThreadPool::commit(std::shared_ptr<Task> task)
{
std::unique_lock<std::mutex> lock(mutex_);
task_.emplace(task);
c_.notify_one();
}
#pragma once
#include <memory>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <vector>
#include <atomic>
class Task
{
public:
virtual void run(){
}
};
class ThreadPool
{
public:
ThreadPool(int thread_num = 5);
virtual ~ThreadPool();
void commit(std::shared_ptr<Task> task);
static void work(ThreadPool *pthis);
std::shared_ptr<Task> get_one_task();
private:
std::vector<std::thread> pools_;
std::mutex mutex_;
std::condition_variable c_;
std::atomic<bool> stop_;
std::queue<std::shared_ptr<Task>> task_;
};
class NewTask : public Task
{
public:
virtual void run(){
//MessageBoxA(NULL, "121", "", MB_OK);
mu.lock();
std::cout << "id =" << std::this_thread::get_id() << std::endl;
mu.unlock();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ThreadPool pool(3);
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
pool.commit(std::make_shared<NewTask>());
std::this_thread::sleep_for(std::chrono::seconds(10));
}