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;
}
                    
相关推荐
汉克老师2 分钟前
CSP-J 2026 初赛试题解析(第三部分:完善程序题(第二题))精讲
c++·csp-j·小学生·学c++编程
kukubuzai8 分钟前
双指针系列二--末尾篇(3道题)
c++·算法·leetcode
君顾117 分钟前
西安24小时自助健身房系统软件开发实战:需求分析与技术落地指南
java·开发语言·健身房
传奇开心果编程18 分钟前
【Rust入门练中学】第4课:函数与所有权入门
开发语言·学习·rust
杜 硕22 分钟前
单链表经典算法题
数据结构·算法
汉克老师31 分钟前
CSP-J 2026 初赛试题解析(第二部分:阅读程序题(第二题))精讲
c++·csp-j·小学生·学c++编程
神仙别闹41 分钟前
基于 C++ 实现(控制台)关键字检索系统
c++
重生之小比特1 小时前
【初阶C++】stack和queue
开发语言·c++·vs·queue
qq_199886871 小时前
第8板块·第1节:主机与设备内存管理基础与统一内存
c++·人工智能·gpu算力·cuda
爱喝水的鱼丶1 小时前
SAP-ABAP:MM 模块供应商主数据开发:字段扩展、分级管控与同步接口开发
开发语言·性能优化·接口·sap·abap·增强·经验交流