利用std::package_task完成一个带返回值的线程池

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

class Task {
public:
    Task(int priority, std::shared_ptr<std::packaged_task<int()>> func)
        : priority_(priority)
        , func_(func)
    {
    }

    bool operator<(const Task& other) const
    {
        return priority_ < other.priority_;
    }

    void execute()
    {
        (*func_)();
    }

private:
    int priority_;
    std::shared_ptr<std::packaged_task<int()>> func_;
};

class TaskPool {
public:
    TaskPool(size_t numThreads)
        : stop(false)
    {
        for (size_t i = 0; i < numThreads; ++i) {
            threads.emplace_back([this] {
                while (true) {
                    std::unique_lock<std::mutex> lock(mutex);
                    condition.wait(lock, [this] {
                        return stop || !tasks.empty();
                    });
                    if (stop && tasks.empty()) {
                        return;
                    }
                    Task task = tasks.top();
                    tasks.pop();
                    lock.unlock();
                    task.execute();
                }
            });
        }
    }

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

    template <typename Func>
    std::future<int> enqueue(int priority_, Func&& func_)
    {
        auto task = std::make_shared<std::packaged_task<int()>>(std::forward<Func>(func_));
        std::future<int> result = task->get_future();
        std::unique_lock<std::mutex> lock(mutex);
        tasks.emplace(priority_, task);
        lock.unlock();
        condition.notify_one();
        return result;
    }

private:
    std::vector<std::thread> threads;
    std::priority_queue<Task> tasks;
    std::mutex mutex;
    std::condition_variable condition;
    bool stop;
};

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

    auto task1 = pool.enqueue(0, [] {
        // 执行优先级为0的任务
        std::cout << "Task with priority 0 executed in thread " << std::this_thread::get_id() << std::endl;
        return 42;
    });

    auto task2 = pool.enqueue(1, [] {
        // 执行优先级为1的任务
        std::cout << "Task with priority 1 executed in thread " << std::this_thread::get_id() << std::endl;
        return 3.14;
    });

    auto task3 = pool.enqueue(0, [] {
        // 执行优先级为0的任务
        std::cout << "Another task with priority 0 executed in thread " << std::this_thread::get_id() << std::endl;
        return -1;
    });

    // 等待任务池中的任务完成
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 获取任务结果
    int result1 = task1.get();
    int result2 = task2.get();
    int result3 = task3.get();

    std::cout << "Result 1: " << result1 << std::endl;
    std::cout << "Result 2: " << result2 << std::endl;
    std::cout << "Result 3: " << result3 << std::endl;

    return 0;
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值