悉野小楼

导航

c++简单的线程池

#include <iostream>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <thread>

class ThreadPool {
public:
    using Task = std::function<void()>;

    // 构造:启动 threadNum 个工作线程
    explicit ThreadPool(size_t threadNum) : stop(false) {
        for (size_t i = 0; i < threadNum; ++i) {
            workers.emplace_back([this] { worker(); });
        }
    }

    // 析构:停止线程池
    ~ThreadPool() {
        {
            std::lock_guard<std::mutex> lock(mtx);
            stop = true;
        }
        cv.notify_all();  // 唤醒所有线程退出

        for (auto& t : workers) {
            if (t.joinable()) t.join();
        }
    }

    // 提交任务(生产者)
    template <class F>
    void enqueue(F&& f) {
        {
            std::lock_guard<std::mutex> lock(mtx);
            tasks.emplace(std::forward<F>(f));
        }
        cv.notify_one();  // 唤醒一个消费者
    }

private:
    // 工作线程(消费者)
    void worker() {
        while (true) {
            Task task;

            {
                std::unique_lock<std::mutex> lock(mtx);
                // 等待:不停止 且 队列为空 → 等待
                cv.wait(lock, [this] { return stop || !tasks.empty(); });

                // 线程池停止且队列为空 → 退出
                if (stop && tasks.empty()) return;

                // 取任务
                task = std::move(tasks.front());
                tasks.pop();
            }

            // 执行任务(解锁后执行,避免长时间占锁)
            if (task) task();
        }
    }

private:
    std::vector<std::thread> workers;    // 工作线程
    std::queue<Task> tasks;              // 任务队列
    std::mutex mtx;                      // 互斥锁
    std::condition_variable cv;          // 条件变量
    bool stop;                           // 停止标志
};

// 测试
int main() {
    ThreadPool pool(4);  // 4个线程

    // 提交8个任务
    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            printf("task %d run by thread %lu\n",
                   i, std::this_thread::get_id());
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
        });
    }

    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "all tasks done\n";
    return 0;
}

 

posted on 2026-04-14 16:45  悉野  阅读(4)  评论(0)    收藏  举报