728x90
반응형

async 3

[C++] std::async

std::async는 std::task 클래스 기반으로 만들어진 클래스로 thread를 만들 때 사용한다. std::async는 std::thread와 달리 내부적으로 thread pool을 만들어 thread를 관리하며 std::thread보다 안정적이며 프로그래머가 사용하기 편하다. std::async는 반환 값을 std::future로 받는다. #include #include using namespace std; void print(char id) { for (int i = 0; i < 10; i++) { printf("thread no : %c , Count : %d \n", id, i); } } int main() { std::future a = std::async(std::launch::asy..

[C++] thread에서 return 값 받기 (promise/future)

C++11 이후에는 이 추가되었으며 future, promise를 통해서 값이나 예외를 저장할 수 있다. 생성하려는 Thread에 Promise를 매개변수로 전달해서 받아올 수 있다. 미래에(future) thread가 원하는 데이터를 돌려 주겠다고 약속(promise)하는 것이라고 할 수 있다. #include #include #include #include void ThreadFunc(std::promise& retVal) { retVal.set_value(1); } int main() { std::promise p; std::future f = p.get_future(); std::thread th1(ThreadFunc, std::ref(p)); th1.join(); std::cout

728x90
반응형