std::funture和std::promise

#include <iostream>
#include <thread>
#include <future>

void calculateResult(std::promise<int>& promiseObj) {
	// 模拟耗时计算
	std::this_thread::sleep_for(std::chrono::seconds(2));

	// 设置结果到 promise 中
	promiseObj.set_value(42);
}

int main() {
	// 创建一个 promise 对象
	std::promise<int> promiseObj;

	// 获取与 promise 关联的 future
	std::future<int> futureObj = promiseObj.get_future();

	// 启动一个新的线程执行计算
	std::thread workerThread(calculateResult, std::ref(promiseObj));

	// 在主线程中等待任务完成,并获取结果
	int result = futureObj.get();

	std::cout << "Result: " << result << std::endl;

	// 等待工作线程结束
	workerThread.join();

	return 0;
}

使用future和promise可以获取到线程执行函数的结果,类似C#实现

#include <iostream>
#include <thread>
#include <future>
#include <vector>
#include <functional>
#include <queue>
class ThreadPool {
public:
    explicit 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(mutex);
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });

                        if (stop && tasks.empty()) {
                            return;
                        }

                        task = std::move(tasks.front());
                        tasks.pop();
                    }

                    task();
                }
                });
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(mutex);
            stop = true;
        }

        condition.notify_all();

        for (std::thread& thread : threads) {
            thread.join();
        }
    }

    template <class F, class... Args>
    auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared<std::packaged_task<return_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

        std::future<return_type> result = task->get_future();

        {
            std::unique_lock<std::mutex> lock(mutex);
            if (stop) {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }

            tasks.emplace([task]() { (*task)(); });
        }

        condition.notify_one();

        return result;
    }

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

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

int calculateResult() {
    // 模拟耗时计算
    std::this_thread::sleep_for(std::chrono::seconds(2));

    return 42;
}

int main() {
    ThreadPool pool(4);

    std::future<int> futureObj = pool.enqueue(calculateResult);

    int result = futureObj.get();

    std::cout << "Result: " << result << std::endl;

    return 0;
}

在线程池中获取线程执行函数的返回值时,通常使用 std::future 而不是 std::promise 来传递返回值。这是因为线程池内部已经管理了任务的执行和结果的传递,你只需要将任务提交给线程池,并使用 std::future 来获取结果。

线程池内部一般会使用一个任务队列来存储待执行的任务,并使用一个线程池管理器来调度任务的执行。当你向线程池提交任务时,线程池会选择一个空闲的线程来执行任务,并将结果存储在与任务关联的 std::future 对象中。

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vegetablesssss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值