Skip to content

Std::future

Future란 어떤 비동기적인 처리를 통해서 앞으로 얻게 될 값이 있다고 할 때 유용하다.

"Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions:

  • std::async
  • promise::get_future
  • packaged_task::get_future

Example

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <vector>
#include <string>
#include <future>

int Calc()
{
    std::cout << "Calc();" << std::endl;
    for (int i = 0; i < 10; ++i) {
        std::cout << i << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    return 42;
}

void DoStuff()
{
    std::cout << "DoStuff();" << std::endl;
    for (int i = 100; i < 105; ++i) {
        std::cout << i << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main(int argc, _TCHAR* argv[])
{
    std::cout << "Main Thread" << std::endl;
    std::future<int> future = std::async(Calc);
    DoStuff();
    std::cout << "The Calc() answer is " << future.get() << std::endl;
    return 0;
}

See also

Favorite site