简单的线程池示例

线程池可以有效地管理和重用线程资源,避免频繁创建和销毁线程带来的开销。以下是一个简单的线程池示例。

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

class ThreadPool {
public:
    ThreadPool(size_t numThreads);
    ~ThreadPool();

    void enqueue(std::function<void()> func);

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;

    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;

    void worker();
};

ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
    for (size_t i = 0; i < numThreads; ++i) {
        workers.emplace_back([this] { this->worker(); });
    }
}

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

void ThreadPool::enqueue(std::function<void()> func) {
    {
        std::unique_lock<std::mutex> lock(queueMutex);
        tasks.push(func);
    }
    condition.notify_one();
}

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

// 示例使用
void exampleTask(int n) {
    std::cout << "Task " << n << " is being processed by thread " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

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

    for (int i = 0; i < 10; ++i) {
        pool.enqueue([i] { exampleTask(i); });
    }`在这里插入代码片`

    std::this_thread::sleep_for(std::chrono::seconds(5)); // 保证主线程等待足够长的时间让线程池处理完任务
    return 0;
}

相关推荐

  1. 简单线示例

    2024-06-17 02:28:03       32 阅读
  2. 简易线实现

    2024-06-17 02:28:03       44 阅读
  3. 简易线实现

    2024-06-17 02:28:03       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-17 02:28:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-17 02:28:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-17 02:28:03       82 阅读
  4. Python语言-面向对象

    2024-06-17 02:28:03       91 阅读

热门阅读

  1. 破解视频会员(你我都懂)

    2024-06-17 02:28:03       33 阅读
  2. leetcode122-Best Time to Buy and Sell Stock II

    2024-06-17 02:28:03       27 阅读
  3. Github 2024-06-11Python开源项目日报 Top10

    2024-06-17 02:28:03       38 阅读
  4. 某文旅集团定岗定编项目成功案例纪实

    2024-06-17 02:28:03       30 阅读
  5. 2024.06.03 校招 实习 内推 面经

    2024-06-17 02:28:03       33 阅读
  6. linux信息查询

    2024-06-17 02:28:03       33 阅读