如何设计一个线程池

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

以下不念给出的是一个简单的线程池设计思路:

  1. 线程池的结构:创建一个线程池类,其中包含一个任务队列和一定数量的工作线程。
  2. 任务类:创建一个任务类,用于表示需要在线程池中执行的具体任务。任务类中应包含任务的执行逻辑。
  3. 任务队列:使用一个线程安全的队列来存储待执行的任务。当有新的任务提交时,将任务加入任务队列。
  4. 线程管理:创建一定数量的工作线程,这些线程会循环地从任务队列中取任务并执行。线程执行完一个任务后,继续尝试获取并执行下一个任务。
  5. 线程同步:使用互斥锁等机制来保护任务队列,防止多个线程同时访问导致数据竞争。
  6. 任务执行:工作线程从任务队列中获取任务,执行任务的执行逻辑。执行完任务后,线程可以等待新任务或者被销毁,具体取决于线程池的设计。
  7. 线程池的生命周期管理:提供线程池的初始化、销毁等方法,确保线程池的正常运行和释放占用的资源。
图片[1]-如何设计一个线程池-不念博客

给个例子:

#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;
}
© 版权声明
THE END
喜欢就支持一下吧
点赞130赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称

    暂无评论内容