c++11 : packaged_task, async, promise, future, shared_future

本文介绍了C++11中的异步操作概念,包括packaged_task、async、promise、future和shared_future。packaged_task用于封装函数,便于异步操作,其结果可通过future获取。async则在新线程中立即执行函数,同样返回future。promise用于封装值,通过future在多线程间同步获取。shared_future与future类似,但允许多个拷贝,并在最后一个拷贝删除前保持有效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

packaged_task

把一個function包起來,方便異步操作。而返回值可以用future取得.

auto sleep = [](){
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 1;
};
std::packaged_task<int()> task(sleep);

auto f = task.get_future();
task(); // invoke the function

// You have to wait until task returns. Since task calls sleep
// you will have to wait at least 1 second.
std::cout << "You can see this after 1 second\n";

// However, f.get() will be available, since task has already finished.
std::cout << f.get() << std::endl;

async

把一個function包起來,而且馬上在新的線程執行(packaged_task會在當前線程執行,會阻塞當前線程)。而返回值可以用future取得.

auto sleep = [](){
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 1;
};
auto f = std::async(std::launch::async, sleep);
std::cout << "You can see this immediately!\n";

// However, the value of the future will be available after sleep has finished
// so f.get() can block up to 1 second.
std::cout << f.get() << "This will be shown after a second!\n";

promise , future

Promise把一個值包起來,容許用future取得其值,提供同步點。而future是提供一個機制,同步地在多線程間取得function或variable的值。

// promise example
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int (std::future<int>& fut) {
  int x = fut.get();
  std::cout << "value: " << x << '\n';
}

int main ()
{
  std::promise<int> prom;                      // create promise

  std::future<int> fut = prom.get_future();    // engagement with future

  std::thread th1 (print_int, std::ref(fut));  // send future to new thread

  prom.set_value (10);                         // fulfill promise
                                               // (synchronizes with getting the future)
  th1.join();
  return 0;
}

shared_future

跟future一樣,不過容許有多個copy.
Lifetime跟shared pointer一樣,在最後一個copy被刪之前都還有效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值