반응형

 

async 를 실행할대 인자는 대표적으로 두개가 있다

 

Specifies the launch policy for a task executed by the std::async function. 

std::launch is an enumeration used as BitmaskType.

The following constants denoting individual bits are defined by the standard library:

Constant Explanation
std::launch::async the task is executed on a different thread, potentially by creating and launching it first
std::launch::deferred the task is executed on the calling thread the first time its result is requested (lazy evaluation)

 

thread 를 굳이 만들지 않고 lock_guard 나 간편하게 비동기로 처리 하고 싶을 때 사용 할 수 있다

ex) 파일 로딩..

 

  • std::future  쓰레드 만들때 좀 더 간단한 방식으로 만드는 형태, 간단하게 쓰일 때 유용
  • calculate 를 async 방식으로 호출 하는 것

  • 대표적으론 두가지 혼합해서 한가지 총 3가지 방식이 있다
    • std::launch::deffered : 지연된 연산(lazy evaluation)인데 지연해서 실행해라 라는 얘기
      get() 를 만날때 실행된다

    • std::launch::async : 별도의 스레드를 만들어서 실행하라는 것
      실제 스레드 개수가 늘어나는것을 Thread 창에서 확인 할수 있다
      스레드를 별도로 만들지 않아도 내부적으로 알아서 만들어서 비동기로 실행함  ex) 데이터 파일 로딩시..
      get() 함수를 통해 join 같은효과를 낼 수 있으며 결과 값을 반환 받을 수 있다

    • std::launch::deffered | std::launch::async : 둘 중에 아무거나 골라서 실행 하라는 것 



 

#include "pch.h"
#include <iostream>
#include "CorePch.h"
#include <thread>	
#include <mutex>
#include "AccountManager.h"
#include "UserManager.h"
#include <chrono>
#include <future>
#include "windows.h"

using namespace std;

int64 calculate()
{
	int64 sum = 0;
	for (int32 i = 0; i < 100'000; ++i)
	{
		sum += 1;
	}
	return sum;
}


int main()
{
	{
		//std::future  쓰레드 만들때 좀 더 간단한 방식으로 만드는 형태, 간단하게 쓰일 때 유용
		//calculate 를 async 방식으로 호출 하는 것
		/*
		* std::launch::deffered : 지연된 연산(lazy evaluation)인데 지연해서 실행해라 라는 얘기
		  std::launch::async : 별도의 스레드를 만들어서 실행하라는 것
		  std::launch::deffered | std::launch::async : 둘 중에 아무거나 골라서 실행 하라는 것 
		*/
		//실제 스레드 개수가 늘어나는것을 Thread 창에서 확인 할수 있다
		//스레드를 별도로 만들지 않아도 내부적으로 알아서 만들어서 비동기로 실행함  ex) 데이터 파일 로딩시..
		std::future<int64> future = std::async(std::launch::async, calculate);		//비 동기 호출, calculate 가 호출 됨

		//이후에 다른 코드를 작성하다가 
		//시간이 지나서 해당 결과를 필요할대 꺼내 올 수 있다
		int64 sum = future.get();		//get 을 만나면 이때까지 스레드가 실행 안됐다면 대기했다가 결과 반환



		std::future<int64> futureDef = std::async(std::launch::deferred, calculate);		//이건 스레드가 아니고 나중에 호출 하겠다는 얘기임

		//실제 스레드 개수가 늘어나지 않는 다는 것을 Thread 창에서 확인 할 수 있다
		int64 sum2 = futureDef.get();		//이때 실행 됨

	}

	return 0;
}

 

 

 

ref : https://en.cppreference.com/w/cpp/thread/launch

반응형

+ Recent posts