温馨提示×

c++线程池使用的方法是什么

c++
小亿
94
2024-01-19 00:21:32
栏目: 编程语言

在C++中使用线程池通常需要以下步骤:

  1. 包含 <thread> 头文件,用于创建线程。
  2. 创建一个线程池类,该类包含一个线程池容器和一个任务队列。
  3. 定义一个任务类,该类包含一个函数指针和函数参数。
  4. 在线程池类中定义一个添加任务的方法,该方法将任务添加到任务队列中。
  5. 在线程池类中定义一个执行任务的方法,该方法从任务队列中取出任务并执行。
  6. 在主函数中创建线程池对象,并调用添加任务的方法添加任务。
  7. 启动线程池对象的执行任务方法,线程池会自动执行添加的任务。

以下是一个简单的C++线程池示例代码:

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

class ThreadPool {
public:
    ThreadPool(int numThreads) : stop(false) {
        for (int i = 0; i < numThreads; ++i) {
            threads.emplace_back(std::bind(&ThreadPool::worker, this));
        }
    }

    template <class F, class... Args>
    void addTask(F&& f, Args&&... args) {
        tasks.emplace(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
    }

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

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

    void worker() {
        while (true) {
            std::function<void()> task;
            {
                std::unique_lock<std::mutex> lock(mutex);
                condition.wait(lock, [this]() { return stop || !tasks.empty(); });
                if (stop && tasks.empty()) {
                    return;
                }
                task = std::move(tasks.front());
                tasks.pop();
            }
            task();
        }
    }
};

void printHello() {
    std::cout << "Hello" << std::endl;
}

int main() {
    ThreadPool pool(4);

    for (int i = 0; i < 8; ++i) {
        pool.addTask(printHello);
    }

    return 0;
}

在上述示例中,线程池类 ThreadPool 包含了一个线程池容器 threads 和一个任务队列 tasks。通过调用 addTask 方法,可以将任务添加到任务队列中。在 worker 方法中,线程池线程会不断从任务队列中取出任务并执行。在主函数中,创建了一个具有4个线程的线程池对象,并添加了8个打印Hello的任务。

0