多线程之C++11跨平台线程池

本文详细介绍了如何使用C++实现一个简单的线程池,包括线程的创建、任务的队列管理和停止条件的控制。通过`std::thread`,`std::mutex`,和`std::condition_variable`实现了高效的并发处理。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <vector>
using namespace std;

class ThreadPool {
public:
    ThreadPool(int numThreads) : stop(false) {
        for (int i = 0; i < numThreads; ++i) {
            threads.emplace_back([this] {
                while (true) {
                    unique_lock<mutex> lock(mtx);
                    condition.wait(lock, [this] { return stop || !tasks.empty(); });
                    if (stop && tasks.empty()) {
                        return;
                    }
                    function<void()> task(move(tasks.front()));
                    tasks.pop();
                    lock.unlock();
                    task();
                }
                });
        }
    }

    ~ThreadPool() {
        {
            unique_lock<mutex> lock(mtx);
            stop = true;
        }
        condition.notify_all();
        for (thread& thread : threads) {
            thread.join();
        }
    }

    template<typename F, typename... Args>
    void enqueue(F&& f, Args&&... args) {
        function<void()> task(bind(forward<F>(f), forward<Args>(args)...));
        {
            unique_lock<mutex> lock(mtx);
            tasks.emplace(move(task));
        }
        condition.notify_one();
    }

private:
    vector<thread> threads;
    queue<function<void()>> tasks;
    mutex mtx;
    condition_variable condition;
    bool stop;
};

int main() {
    ThreadPool pool(4);
    for (int i = 0; i < 10; ++i) {
        pool.enqueue([i] {
            cout << "Task " << i << " is running in thread " << this_thread::get_id() << endl;
            this_thread::sleep_for(chrono::seconds(1));
            cout << "Task " << i << " is done" << endl;
            });
    }
    return 0;
}

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值