线程池如何设计?

2023-12-11 0 1,137

设计一个线程池涉及到多个方面,包括线程的创建与销毁、任务的提交与执行、线程间的通信等。

线程池的结构:创建一个线程池类,其中包含一个任务队列和一定数量的工作线程。

任务类:创建一个任务类,用于表示需要在线程池中执行的具体任务。任务类中应包含任务的执行逻辑。

任务队列:使用一个线程安全的队列来存储待执行的任务。当有新的任务提交时,将任务加入任务队列。

线程管理:创建一定数量的工作线程,这些线程会循环地从任务队列中取任务并执行。线程执行完一个任务后,继续尝试获取并执行下一个任务。

线程同步:使用互斥锁等机制来保护任务队列,防止多个线程同时访问导致数据竞争。

任务执行:工作线程从任务队列中获取任务,执行任务的执行逻辑。执行完任务后,线程可以等待新任务或者被销毁,具体取决于线程池的设计。

线程池的生命周期管理:提供线程池的初始化、销毁等方法,确保线程池的正常运行和释放占用的资源。
线程池如何设计?
给个例子:


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

class ThreadPool {
public:
    ThreadPool(size_t numThreads) : stop(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function<void()> task;

                    {
                        std::unique_lock<std::mutex> lock(queueMutex);
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });

                        if (stop && tasks.empty()) {
                            return;
                        }

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

                    task();
                }
            });
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }

        condition.notify_all();

        for (std::thread &worker : workers) {
            worker.join();
        }
    }

    template<class F>
    void enqueue(F&& f) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.emplace(std::forward<F>(f));
        }

        condition.notify_one();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;
};

int main() {
    ThreadPool pool(4);

    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            std::cout << "Task " << i << " executed by thread " << std::this_thread::get_id() << std::endl;
        });
    }

    // Sleep to allow threads to finish
    std::this_thread::sleep_for(std::chrono::seconds(2));

    return 0;
}

本文章已结束,如转载请注明:汇站网 » 线程池如何设计?

收藏 (0)

微信支付 微信扫一扫

支付宝支付 支付宝扫一扫

打赏二维码
点赞 (0)

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

联系官方客服

为您解决烦忧 - 24小时在线 专业服务