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

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        // std::cout
#include      // std::ref
#include          // std::thread
#include          // 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被刪之前都還有效

你可能感兴趣的:(c++11 : packaged_task, async, promise, future, shared_future)