C++future与promise异步

C++future与promise异步 Cfuture与promise异步future和promise是C标准库提供的异步结果传递机制。promise设置值future获取值两者通过共享状态通信。std::async启动异步任务并返回future。#include#include#include#include#includeint compute_square(int x) {std::this_thread::sleep_for(std::chrono::milliseconds(200));return x * x;}void async_basics() {std::future result std::async(std::launch::async, compute_square, 25);std::cout Computing...\n;int value result.get();std::cout Square: value \n;}启动策略控制执行方式。void launch_policies() {auto deferred std::async(std::launch::deferred, []() {std::cout Deferred execution\n;return 42;});auto async_task std::async(std::launch::async, []() {std::cout Async execution\n;return 100;});std::cout Getting deferred: deferred.get() \n;std::cout Getting async: async_task.get() \n;}promise手动设置值。void promise_demo() {std::promise promise;std::future future promise.get_future();std::thread producer([promise]() {std::this_thread::sleep_for(std::chrono::milliseconds(100));promise.set_value(42);std::cout Promise set\n;});std::cout Waiting for value...\n;int value future.get();std::cout Got value: value \n;producer.join();}promise传递异常。void promise_exception() {std::promise promise;std::future future promise.get_future();std::thread worker([promise]() {try {throw std::runtime_error(Task failed);} catch (...) {promise.set_exception(std::current_exception());}});try {int value future.get();} catch (const std::exception e) {std::cout Caught: e.what() \n;}worker.join();}packaged_task包装可调用对象。void packaged_task_demo() {std::packaged_task task([](int a, int b) {std::this_thread::sleep_for(std::chrono::milliseconds(50));return a b;});std::future result task.get_future();std::thread t(std::move(task), 10, 20);std::cout Result: result.get() \n;t.join();}线程池结合future。class ThreadPool {std::vector workers_;std::queue tasks_;std::mutex mtx_;std::condition_variable cond_;std::atomic stop_{false};public:explicit ThreadPool(size_t n) {for (size_t i 0; i n; i) {workers_.emplace_back([this]() {while (true) {std::function task;{std::unique_lock lock(mtx_);cond_.wait(lock, [this]() {return stop_.load() || !tasks_.empty();});if (stop_.load() tasks_.empty()) return;task std::move(tasks_.front());tasks_.pop();}task();}});}}~ThreadPool() {stop_.store(true);cond_.notify_all();for (auto w : workers_) if (w.joinable()) w.join();}templateauto enqueue(F f, Args... args) - std::future {using return_type decltype(f(args...));auto task std::make_shared(std::bind(std::forward(f), std::forward(args)...));std::future result task-get_future();{std::lock_guard lock(mtx_);tasks_.emplace([task]() { (*task)(); });}cond_.notify_one();return result;}};void pool_with_future() {ThreadPool pool(4);std::vector results;for (int i 0; i 8; i) {results.push_back(pool.enqueue(compute_square, i 1));}int sum 0;for (auto f : results) {sum f.get();}std::cout Sum of squares 1-8: sum \n;}shared_future允许多个消费者。void shared_future_demo() {std::promise promise;std::shared_future shared promise.get_future().share();std::vector consumers;for (int i 0; i 5; i) {consumers.emplace_back([shared, i]() {int value shared.get();std::cout Consumer i got: value \n;});}std::thread producer([promise]() {std::this_thread::sleep_for(std::chrono::milliseconds(100));promise.set_value(42);});for (auto c : consumers) c.join();producer.join();}等待多个future。void wait_for_futures() {std::vector futures;for (int i 0; i 5; i) {futures.push_back(std::async(std::launch::async, [i]() {std::this_thread::sleep_for(std::chrono::milliseconds(i * 50));return i * 10;}));}for (auto f : futures) {auto status f.wait_for(std::chrono::milliseconds(30));if (status std::future_status::ready) {std::cout Ready: f.get() \n;} else {std::cout Not ready yet\n;}}}future是C异步编程的基础组件与promise、async和packaged_task配合使用。