std::async
- 주어진 함수를 비동기 (asynchronous)로 수행하는 함수 템플릿
- 기존에 작성된 함수를 간단하게 스레드로 수행할 수 있다.
- 일반적인 구현은 스레드 풀 사용
- std::future 반환
1. std::async 기본 예제
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
using namespace std::literals;
int add(int a, int b) {
std::this_thread::sleep_for(2s);
return a+b;
}
int main() {
std::future<int> ft = std::async(add, 10, 20);
std::cout << "continue main" << std::endl;
int ret = ft.get();
std::cout << "result: " << ret << std::endl;
}
- 위 예제에서 ft.get()을 호출하지 않아도 future의 소멸자에서 get()을 호출하여 쓰레드의 종료를 대기한다.
- std::async를 반환받지 않은 경우? async를 호출한 라인에서 임시객체가 생성되고 임시객체가 파괴되는데 임시객체가 파괴할때 소멸자에서 future의 get()이 호출되어 쓰레드 종료를 기다리게됨. 따라서, 쓰레드가 종료될때까지 이후 라인이 실행되지 않음!
- std::async의 반환이 아니라 단순히 std::future만 선언했을 경우는 future의 소멸자에서 get()을 호출하지 않는다.
2. std::async의 std::launch 옵션
- std::launch:async 옵션을 주면 async가 생성되자마자 다른 쓰레드가 생성되어 실행된다.
- std::launch::deferred 옵션을 주면 async가 생성된 이후에 바로 쓰레드가 시작되지않고 future의 get API가 호출될때 같은 쓰레드에서 실행된다.
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
using namespace std::literals;
int add(int a, int b) {
std::cout << "add: " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(2s);
return a+b;
}
int main() {
// std::future<int> ft = std::async(std::launch::async, 10, 20); // 다른 쓰레드 생성
// std::future<int> ft = std::async(std::launch::deferred, 10, 20); // 지연된 실행
std::cout << "continue main : " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(2s);
int ret = ft.get();
std::cout << "result: " << ret << std::endl;
}
728x90
'Language > C++' 카테고리의 다른 글
[C++] std::jthread (0) | 2025.01.06 |
---|---|
[C++] std::packaged_task (0) | 2024.12.18 |
[C++] std::promise, std::future (0) | 2024.12.04 |
[C++] std::ref, std::reference_wrapper (1) | 2023.09.01 |
[C++] std::thread (1) | 2023.09.01 |
댓글