温馨提示×

C++中如何利用线程池库进行任务调度

c++
小樊
82
2024-09-06 10:37:59
栏目: 编程语言

在 C++ 中,可以使用线程池库来进行任务调度。这里我们将介绍一个简单的线程池库,并展示如何使用它来调度任务。

首先,需要安装线程池库。在 Ubuntu 系统下,可以通过以下命令安装:

sudo apt-get install libboost-all-dev

接下来,创建一个名为 thread_pool.cpp 的文件,然后编写以下代码:

#include<iostream>
#include<boost/asio.hpp>
#include<boost/bind.hpp>
#include<boost/thread.hpp>

class ThreadPool {
public:
    ThreadPool(size_t num_threads) : work_(io_service_) {
        for (size_t i = 0; i < num_threads; ++i) {
            threads_.create_thread(boost::bind(&boost::asio::io_service::run, &io_service_));
        }
    }

    ~ThreadPool() {
        io_service_.stop();
        threads_.join_all();
    }

    template<typename F>
    void enqueue(F f) {
        io_service_.post(f);
    }

private:
    boost::asio::io_service io_service_;
    boost::asio::io_service::work work_;
    boost::thread_group threads_;
};

void task1() {
    std::cout << "Task 1 is running in thread "<< boost::this_thread::get_id()<< std::endl;
}

void task2() {
    std::cout << "Task 2 is running in thread "<< boost::this_thread::get_id()<< std::endl;
}

int main() {
    ThreadPool pool(4); // 创建一个包含 4 个线程的线程池

    pool.enqueue(task1); // 将任务 1 添加到线程池
    pool.enqueue(task2); // 将任务 2 添加到线程池

    return 0;
}

在这个例子中,我们创建了一个名为 ThreadPool 的类,它使用 boost::asio::io_serviceboost::thread_group 来管理线程。ThreadPool 类提供了一个 enqueue 方法,用于将任务添加到线程池。

我们定义了两个简单的任务 task1task2,并在 main 函数中创建了一个包含 4 个线程的线程池。然后,我们将这两个任务添加到线程池中。

要编译这个程序,请使用以下命令:

g++ -o thread_pool thread_pool.cpp -lboost_system -lboost_thread -pthread

最后,运行生成的可执行文件:

./thread_pool

输出结果类似于:

Task 1 is running in thread 140396678533888
Task 2 is running in thread 140396678533376

这表明任务已经在线程池中的线程上运行。

0