首页 >后端开发 >C++ >如何在C 11中高效实现线程池以避免重复的线程创建和删除开销?

如何在C 11中高效实现线程池以避免重复的线程创建和删除开销?

Patricia Arquette
Patricia Arquette原创
2024-12-13 14:27:11531浏览

How to Efficiently Implement a Thread Pool in C  11 to Avoid Repeated Thread Creation and Deletion Overhead?

C 11 中的线程池

问题: 重复创建和删除线程的成本很高。我们如何建立一个持久的线程池来处理任务而不产生这种开销?

解决方案:

实现 ThreadPool 类

为了创建一个高效的线程池,我们首先定义ThreadPool类:

class ThreadPool {
public:
    void Start();
    void QueueJob(const std::function<void()>& job);
    void Stop();
    bool busy();

private:
    void ThreadLoop();
    bool should_terminate = false;
    std::mutex queue_mutex;
    std::condition_variable mutex_condition;
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> jobs;
};

1。 ThreadPool::Start:

根据系统能力创建固定数量的线程:

void ThreadPool::Start() {
    const uint32_t num_threads = std::thread::hardware_concurrency();
    for (uint32_t ii = 0; ii < num_threads; ++ii) {
        threads.emplace_back(std::thread(&ThreadPool::ThreadLoop,this))
    }
}

2。 ThreadPool::ThreadLoop:

等待新任务的无限循环:

void ThreadPool::ThreadLoop() {
    while (true) {
        std::function<void()> job;
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            mutex_condition.wait(lock, [this] {
                return !jobs.empty() || should_terminate;
            });
            if (should_terminate) {
                return;
            }
            job = jobs.front();
            jobs.pop();
        }
        job();
    }
}

3. ThreadPool::QueueJob:

向池中添加新任务:

void ThreadPool::QueueJob(const std::function<void()>& job) {
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        jobs.push(job);
    }
    mutex_condition.notify_one();
}

4. ThreadPool::busy:

检查池中是否有活动作业:

bool ThreadPool::busy() {
    bool poolbusy;
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        poolbusy = !jobs.empty();
    }
    return poolbusy;
}

5. ThreadPool::Stop:

优雅地停止线程池:

void ThreadPool::Stop() {
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        should_terminate = true;
    }
    mutex_condition.notify_all();
    for (std::thread& active_thread : threads) {
        active_thread.join();
    }
    threads.clear();
}

用法:

thread_pool->QueueJob([] { /* ... */ });

此实现提供了一个动态的线程池,线程持续运行并等待添加任务。

以上是如何在C 11中高效实现线程池以避免重复的线程创建和删除开销?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn