본문 바로가기

프로그래밍 언어 노트/C++ | Modern C++

[Modern C++] C++ 코루틴

#include <iostream>
#include <future>
#include <Windows.h>
using namespace std;

future<int> async_add(int a, int b)
{
	auto fut = std::async([=]() {
		int c = a + b;
		return c;
		});

	return fut;
}

future<int> async_fib(int n)
{
	if (n <= 2)
		co_return 1;

	int a = 1;
	int b = 1;

	// iterate computing fib(n)
	for (int i = 0; i < n - 2; ++i)
	{
		int c = co_await async_add(a, b);
		a = b;
		b = c;
	}

	co_return b;
}
future<void> fib_loop(int number)
{
	for (int i = 1; i < number; ++i)
	{
		cout << co_await async_fib(i) << endl;
	}
}
int main()
{
	cout << "Start" << endl;

	auto f = fib_loop(10);

	while (!f._Is_ready())
	{
		Sleep(1);
		cout << "Main!" << endl;
	}

	cout << endl;
	return 0;
}

https://yizhang82.dev/cpp-coroutines-async-fibonacci

 

C++ coroutine tutorial - computing fibonacci using C++ coroutines

C++ coroutine tutorial using async computation of fibonacci

yizhang82.dev

 

 

 

VS 2019 기준 명령줄 /await 추가 및 최신 컴파일러로 설정 변경

 

co_yield 의 경우 규칙에 맞는 generator 오브젝트 정의해줘야하는듯.

728x90