c++11 线程池
来源:互联网 发布:生肉galgame翻译软件 编辑:程序博客网 时间:2024/06/10 00:11
#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));}
0 0
- c++/c实现线程池
- ThreadPool 线程池[c#]
- ThreadPool 线程池[c#]
- ThreadPool 线程池[c#]
- c实现线程池
- linux c线程池
- ThreadPool 线程池[c#]
- Linux C线程池
- 线程池 c 实现
- Linux C 线程池
- linux c 线程池
- C 线程池 thread_pool
- C/C++ 线程池
- Linux C 线程池
- c/c++线程--3线程池
- Linux C 实现线程池
- c语言实现线程池
- C 语言创建线程池
- hadoop_案例_1
- join
- Git SSH Key生成
- jni/../../Classes/AppDelegate.cpp报错,一次性添加所有cpp文件
- circshift 函数详解
- c++11 线程池
- storm入门及其环境搭建(下)
- Android开发中,那些让你相见恨晚的方法、类或接口
- OpenCV学习笔记(六)—— OpenCV for Android打开相机
- 头插法建立链表
- selector加layer-list的用法
- 面向短信接口开发实例
- hadoop_案例_2
- LeetCode *** 92. Reverse Linked List II