MMOServer
Future(C++)
이야기prog
2025. 3. 13. 21:28
#include "pch.h"
#include <thread>
#include <atomic>
#include <mutex>
#include <future>
int32 ReturnInt32() {
for(int i = 0; i < 10000000; ++i) {}
std::this_thread::sleep_for(1s);
return 100;
}
void Future(std::promise<string>&& promise) {
promise.set_value("Set Message!");
}
int main() {
//std::future<int32> future = std::async(std::launch::async, ReturnInt32);
//int32 tmp = future.get();
//cout << tmp;
std::promise<string> promise;
std::future<string> future = promise.get_future();
thread t1(Future, std::move(promise));
string tmp = future.get();
cout << tmp;
t1.join();
return 0;
}
std::future는 보통 mutex나 condition_variable같이 본격적으로 멀티쓰레드를 사용하겠다기 보다는, 단기로 한번만 비동기적으로 사용하고 싶을 때, 사용한다.
std::async에는 스레드풀에 있는 스레드를 사용해서 비동기적으로 함수를 수행하는것으로,
std::launch::async하고 std::launch::defer이 있는데, defer은 그냥 뒤에 future.get()을 호출 할때 함수를 실행하겠다는 것이고, async는 다른 스레드에 함수를 할당해서 동시에 실행하고 future.get()할 때, 함수의 반환값을 받겠다는 것이다.
promise는 future와 연계해서 사용하는데 future의 값을 받겠다고 약속(?)하는 그런 객체이다.
함수 인자로 std::promise를 직접넣고 promise.set_value()로 promise.get_future()을 받는 future객체에 값을 반환하고
future.get()으로 다른 변수에 값을 집어넣을 수 있다. 보통 이동 연산자로 함수에서 받기때문에 한번 호출하고 소멸한다.