C++11线程池

使用 condition_variable::wait(unique_lock<mutex>&lck, Predicate pred) 时,必须保证条件变量通过notify唤醒的同时,wait 的第二个参数 Predicate 返回 true 了才可以往下走。必须两个条件同时满足,如果notify的时候Predicate返回时false一样的唤不醒线程。

cpp 复制代码
#include <iostream>
#include <future>
#include <chrono>
#include <string>
#include<functional>
#include <queue>

using Task = std::function<void()>;
class ThreaPool
{
public:
    void start() 
    {
        running_ = true;
    }

    bool is_running()
    {
        return running_;
    }

    void stop() 
    {
        std::cout << "stop..." << std::endl;
        running_ = false;
        std::unique_lock<std::mutex> lk(qmutext_);
        tasks_.push([]() { std::cout << "hello pool end " << std::endl;  });
        cond_.notify_all();
    }

    void push_task(Task task) 
    {
        if (!running_)
        {
            return;
        }
        

std::unique_lock<std::mutex> lk(qmutext_);
        tasks_.push(task);
        cond_.notify_one();
    }

    ThreaPool(int count)
    {
        for (int i = 0; i < count; i++)
        {
            pool_.emplace_back([this]() 
            {
                while (true)
                {
                    Task task;
                    {
                        std::unique_lock<std::mutex> lk(qmutext_);
                        std::cout << "wait 1" << std::endl;
                        cond_.wait(lk, [this] {return !running_ || !tasks_.empty(); });
                        std::cout << "wait 2" << std::endl;
                        if (!tasks_.empty())
                        

{
                            task = std::move(tasks_.front());
                            tasks_.pop();
                        }
                    }

                    if (task)
                    {
                        task();
                    }

                    if (!this->is_running())
                    {
                        std::cout << "stoped 1" << std::endl;
                        std::unique_lock<std::mutex> lk(qmutext_);
                        if (tasks_.empty()) {
                            std::cout << "stoped 2" << std::endl;
                            return;
                        }
                    }
                }
            });
        }
    }

~ThreaPool() 
	{
		for (std::thread& worker : pool_) {
			worker.join();
		}
	};

private:
	std::vector<std::thread> pool_;
	std::mutex qmutext_;
	std::condition_variable cond_;
	std::queue< Task > tasks_;
	std::atomic_bool running_{ true };
};

int main()
{
	ThreaPool pool(5);

	std::this_thread::sleep_for(std::chrono::seconds(1));
	pool.push_task([]() { std::cout << "hello pool 1 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 2 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 3 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 4 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 5 \n" << std::endl;  });
    pool.push_task([]() { std::cout << "hello pool 6 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 7 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 8 \n" << std::endl;  });
	pool.push_task([]() { std::cout << "hello pool 9 \n" << std::endl;  });

	std::this_thread::sleep_for(std::chrono::seconds(1));
	pool.stop();
	return 0;
}
                    
相关推荐
Code哈哈笑11 分钟前
【机器学习】支持向量回归(SVR)从入门到实战:原理、实现与优化指南
人工智能·算法·机器学习·回归·svm
小哈里18 分钟前
【pypi镜像源】使用devpi实现python镜像源代理(缓存加速,私有仓库,版本控制)
开发语言·python·缓存·镜像源·pypi
努力学习的小廉22 分钟前
【C++】 —— 笔试刷题day_29
开发语言·c++·算法
小羊在奋斗24 分钟前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
meisongqing30 分钟前
【软件工程】符号执行与约束求解缺陷检测方法
人工智能·算法·软件工程·软件缺陷
电商数据girl31 分钟前
酒店旅游类数据采集API接口之携程数据获取地方美食品列表 获取地方美餐馆列表 景点评论
java·大数据·开发语言·python·json·旅游
天天打码31 分钟前
python版本管理工具-pyenv轻松切换多个Python版本
开发语言·python
CircleMouse31 分钟前
基于 RedisTemplate 的分页缓存设计
java·开发语言·后端·spring·缓存
ktkiko1138 分钟前
顶层架构 - 消息集群推送方案
java·开发语言·架构
楠奕38 分钟前
python中使用neo4j
开发语言·python·neo4j