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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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

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

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

private:
    int priority_;
    std::shared_ptr> 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 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 lock(mutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread& thread : threads) {
            thread.join();
        }
    }

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

private:
    std::vector threads;
    std::priority_queue 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;
}

你可能感兴趣的:(C++,c++)