19.5 작업(Task) 기반 비동기 프로그래밍 async, future, promise
#include <iostream>
#include <future> // async, future, promise
#include <thread>
using namespace std;
int main()
{
// multi-threading
{
int result;
std::thread t([&]{result = 1+2;});
t.join();
cout << result << "\n";
}
// task-based parallelism
{
//std::future<int> fut = ...
auto fut = std::async([]{return 1+2;}); // return이 들어감.
// main thread가 진행되는 것과 별도로 진행.
// 일반적으로 async가 thread보다 더 선호.
// 여기선 fut가 어떤 일을 할 것인가에 대해서 프로그래밍.
cout << fut.get() << "\n"; // return값이 들어올 때 까지 기다린다.
}
// future and promise
{
std::promise<int> prom;
auto fut = prom.get_future(); // std::future<int> 타입.
auto t = std::thread([](std::promise<int>&& prom) // future를 받을 수 있는 존재가 하나 필요해서 promise를 거쳐가는 것. promise를 parameter로 넣어줌. (R-value reference)
{
prom.set_value(1+2); // 값을 넣어주고 있다.
}, std::move(prom));
cout << fut.get() << "\n";
t.join(); // 그래도 join은 해주는 것이 안정적.
}
return 0;
}
#include <iostream>
#include <future> // async, future, promise
#include <thread>
using namespace std;
int main()
{
{
auto f1 = std::async([] {
cout << "async1 start" << "\n";
this_thread::sleep_for(chrono::seconds(2));
cout << "async1 end" << "\n";
});
auto f2 = std::async([]{
cout << "async2 start" << "\n";
this_thread::sleep_for(chrono::seconds(1));
cout << "async1 end" << "\n";
});
std::cout << "Main function" << "\n";
}
return 0;
}
Main function
async1 start
async2 start
async2 end
async1 end // Main function이 먼저 실행된다.
// thread로 바꿨을 경우 async1 -> async2 -> main function 순으로 실행.
future가 없을 경우
#include <iostream>
#include <future> // async, future, promise
#include <thread>
using namespace std;
int main()
{
{
std::async([] {
cout << "async1 start" << "\n";
this_thread::sleep_for(chrono::seconds(2));
cout << "async1 end" << "\n";
});
std::async([]{
cout << "async2 start" << "\n";
this_thread::sleep_for(chrono::seconds(1));
cout << "async1 end" << "\n";
});
std::cout << "Main function" << "\n";
}
return 0;
}
결과
async1 start
async1 end
async2 start
async2 end
Main function
// 앞에서 받아주는 future가 없을 경우 sequential인 것처럼 진행.