C++是一种支持高并发的编程语言,可以使用线程池来管理并发执行的任务。线程池是一种常见的并发编程模型,可以通过复用线程来减少线程创建和销毁的开销,提高程序的性能。

在C++中,可以使用标准库提供的线程和互斥锁来实现一个简单的线程池。以下是一个简单的C++线程池实现的示例代码:

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

class ThreadPool {
public:
    ThreadPool(size_t numThreads) : stop(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            threads.emplace_back([this] {
                while (true) {
                    std::function<void()> task;

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

                    task();
                }
            });
        }
    }

    template<class F>
    void enqueue(F&& func) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.emplace(std::forward<F>(func));
        }
        condition.notify_one();
    }

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

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

// 示例用法
void taskFunc(int id) {
    std::cout << "Task " << id << " is being executed" << std::endl;
}

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

    // 提交10个任务给线程池
    for (int i = 0; i < 10; ++i) {
        threadPool.enqueue([i] { taskFunc(i); });
    }

    // 等待所有任务执行完毕
    std::this_thread::sleep_for(std::chrono::seconds(1));

    return 0;
}

这个线程池实现使用了一个队列来保存待执行的任务,并使用互斥锁和条件变量来实现线程间的同步。在构造函数中创建了指定数量的线程,并在每个线程中不断从任务队列中取出任务并执行。enqueue()方法用于向线程池中提交新的任务。

通过使用线程池,可以方便地管理并发的任务执行,并且可以根据需要动态调整线程池的大小,提高程序的性能和响应能力

C++高并发线程池

原文地址: http://www.cveoy.top/t/topic/hDcR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录