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;
}
                    
相关推荐
胖大和尚4 分钟前
clang 编译器怎么查看在编译过程中做了哪些优化
c++·clang
pumpkin845145 分钟前
Rust 调用 C 函数的 FFI
c语言·算法·rust
lsx20240613 分钟前
CSS 网页布局:从基础到进阶
开发语言
挺菜的16 分钟前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.82416 分钟前
7.6 优先队列| dijkstra | hash | rust
算法
蜗牛沐雨17 分钟前
警惕 Rust 字符串的性能陷阱:`chars().nth()` 的深坑与高效之道
开发语言·后端·rust
2401_858286111 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
钱彬 (Qian Bin)1 小时前
一文掌握Qt Quick数字图像处理项目开发(基于Qt 6.9 C++和QML,代码开源)
c++·开源·qml·qt quick·qt6.9·数字图像处理项目·美观界面
guygg881 小时前
基于matlab的FIR滤波器
开发语言·算法·matlab
双叶8362 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++