Home >Backend Development >C++ >What are the usage scenarios of thread pools in C++ multi-threaded programming?

What are the usage scenarios of thread pools in C++ multi-threaded programming?

WBOY
WBOYOriginal
2024-06-04 19:51:08530browse

Thread pool is used to manage threads and reduce thread overhead by maintaining a pre-allocated thread pool. Specific scenarios include: reducing thread creation and destruction overhead; managing concurrency to prevent resource exhaustion; improving code simplicity and eliminating thread management details.

C++ 多线程编程中线程池的使用场景有哪些?

Usage scenarios of thread pools in C++ multi-threaded programming

The thread pool is a mechanism for managing threads, which can improve Efficiency and performance of multi-threaded programming. In C++, thread pools can be implemented using standard libraries such as std::thread and std::condition_variable.

The following are some common scenarios for using thread pools:

  • Reduce the overhead of thread creation and destruction: Creating and destroying threads is a relatively expensive operation. Thread pools avoid this overhead by maintaining a pool of pre-allocated threads.
  • Manage concurrency: The thread pool can limit the number of threads executing simultaneously, which is very important to prevent system resource exhaustion.
  • Improve code simplicity: Thread pools can simplify multi-threaded programming because it eliminates the tedious details of managing the threads themselves.

Practical case

The following is a use of std::thread and std::condition_variable in C++ Example of implementing a thread pool in:

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

using namespace std;

// 线程池类
class ThreadPool {
public:
    ThreadPool(int num_threads) : stop(false) {
        // 创建指定数量的线程并将其添加到线程池
        for (int i = 0; i < num_threads; i++) {
            threads.emplace_back([this] {
                while (!stop) {
                    unique_lock<mutex> lock(mtx);
                    if (!tasks.empty()) {
                        // 从任务队列中获取任务
                        auto task = tasks.front();
                        tasks.pop();
                        // 执行任务
                        task();
                        // 通知条件变量任务已完成
                        cv.notify_one();
                    } else {
                        // 如果任务队列为空,则等待新任务
                        cv.wait(lock);
                    }
                }
            });
        }
    }

    ~ThreadPool() {
        // 停止所有线程
        stop = true;
        cv.notify_all();

        // 等待所有线程完成
        for (auto& thread : threads) {
            thread.join();
        }
    }

    // 向任务队列添加任务
    void enqueue(function<void()> &&task) {
        unique_lock<mutex> lock(mtx);
        tasks.push(move(task));
        // 通知条件变量有新任务
        cv.notify_one();
    }

private:
    bool stop;  // 线程池停止标志
    mutex mtx;  // 用于保护任务队列和条件变量
    condition_variable cv;  // 用于等待新任务
    queue<function<void()>> tasks;  // 任务队列
    vector<thread> threads;  // 线程池中的线程
};

int main() {
    // 创建具有 4 个线程的线程池
    ThreadPool pool(4);

    // 向线程池添加 10 个任务
    for (int i = 0; i < 10; i++) {
        pool.enqueue([i] {
            cout << "Task " << i << " executed by thread " << this_thread::get_id() << endl;
        });
    }

    return 0;
}

In this example, we create a ThreadPool class that maintains a pre-allocated thread pool. Tasks are added to the task queue through the enqueue function. Threads in the thread pool continuously obtain tasks from the task queue and execute them. When the task queue is empty, the thread waits for the condition variable to be notified that a new task is available.

The output looks like this:

Task 0 executed by thread 139670130218816
Task 1 executed by thread 139670129941952
Task 2 executed by thread 139670130082240
Task 3 executed by thread 139670130226176
Task 4 executed by thread 139670129949696
Task 5 executed by thread 139670130233920
Task 6 executed by thread 139670129957440
Task 7 executed by thread 139670130090080
Task 8 executed by thread 139670130241664
Task 9 executed by thread 139670129965184

The above is the detailed content of What are the usage scenarios of thread pools in C++ multi-threaded programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn