c++

如何在c++中使用线程池

小樊
81
2024-10-16 10:33:14
栏目: 编程语言

在C++中使用线程池可以通过多种方式实现,以下是一些常见的方法:

方法一:使用C++11标准库中的 <thread><future> 头文件

  1. 包含必要的头文件:
#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
  1. 定义线程池类:
class ThreadPool {
public:
    ThreadPool(size_t threads);
    ~ThreadPool();

    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;

private:
    // ...(省略部分代码,与上面的代码相同)...
};
  1. 实现线程池类:
// ...(省略构造函数、析构函数和部分成员函数的实现,与上面的代码相同)...

template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<return_type()>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );

    std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(m);
        if (stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");
        tasks.emplace([task]() { (*task)(); });
    }
    condition.notify_one();
    return res;
}
  1. 使用线程池:
int main() {
    ThreadPool pool(4);

    auto result1 = pool.enqueue([](int a, int b) { return a + b; }, 2, 3);
    auto result2 = pool.enqueue([](int a) { return a * a; }, 5);

    std::cout << "Result 1: " << result1.get() << std::endl;
    std::cout << "Result 2: " << result2.get() << std::endl;

    return 0;
}

方法二:使用第三方库,如 Boost.Asio

Boost.Asio 是一个广泛使用的 C++ 库,它提供了异步 I/O 和线程池等功能。要使用 Boost.Asio 创建线程池,你需要安装 Boost 库并包含相应的头文件。

  1. 包含必要的头文件:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
  1. 定义线程池类:
class ThreadPool {
public:
    ThreadPool(size_t threads);
    ~ThreadPool();

    void enqueue(boost::function<void()> task);

private:
    boost::asio::io_service io_service_;
    std::vector<boost::thread> threads_;
    std::queue<boost::function<void()>> tasks_;
    boost::mutex mutex_;
    boost::condition_variable condition_;
    bool stop_;
};
  1. 实现线程池类:
// ...(省略构造函数、析构函数和部分成员函数的实现,与上面的代码相同)...

void ThreadPool::enqueue(boost::function<void()> task) {
    {
        boost::unique_lock<boost::mutex> lock(mutex_);
        if (stop_)
            throw std::runtime_error("enqueue on stopped ThreadPool");
        tasks_.push(move(task));
    }
    condition_.notify_one();
    if (threads_.size() == 1) {
        threads_[0] = boost::thread([this]() { io_service_.run(); });
    }
}
  1. 使用线程池:
int main() {
    ThreadPool pool(4);

    pool.enqueue([](int a, int b) { std::cout << a + b << std::endl; }, 2, 3);
    pool.enqueue([](int a) { std::cout << a * a << std::endl; }, 5);

    boost::this_thread::sleep_for(boost::chrono::seconds(1));

    return 0;
}

请注意,上述示例仅用于演示目的,实际应用中可能需要根据具体需求进行调整和优化。

0
看了该问题的人还看了