개발 라이브러리 & 툴

MS 비동기 에이전트 라이브러리 소개: #2 Hello World

하늘흐늘 2021. 12. 25. 15:07
반응형

비동기 에이전트 라이브러리(Asynchronous Agent Library)를 사용하여 Hello World를 출력하는 아래 예제를 살펴보겠습니다.

#include <agents.h>
#include <string>
#include <iostream>
#include <sstream>
#include <functional>


using namespace concurrency;
using namespace std;


class agent_01_a : public agent
{
public:
	explicit agent_01_a(ISource<string>& source, ITarget<string>& target)
		: source_(source), target_(target)
	{
	}

protected:
	void run()
	{
		send(target_, string("Hello"));

		string response = receive(source_);

		cout << response << endl;

		done();
	}

private:
	ISource<string>& source_;
	ITarget<string>& target_;
};

class agent_01_b : public agent
{
public:
	explicit agent_01_b(ISource<string>& source, ITarget<string>& target)
		: source_(source), target_(target)
	{
	}

protected:
	void run()
	{
		ostringstream oss;

		string request = receive(source_);

		oss << request;
		oss << " ";
		oss << "World";

		send(target_, oss.str());

		done();
	}

private:
	ISource<string>& source_;
	ITarget<string>& target_;
};

int main(int argc, char* argv[])
{
	unbounded_buffer<string> message_block1;
	overwrite_buffer<string> message_block2;

	agent_01_a agent_a(message_block2, message_block1);
	agent_01_b agent_b(message_block1, message_block2);

	agent_a.start();
	agent_b.start();

	agent::wait(&agent_a);
	agent::wait(&agent_b);

	return 0;
}

결과는 아래와 같습니다.

Hello World

간단한 쌍방향 메세지 블록을 만들고 Hello World를 출력하는 예제입니다.
예제는 간단하지만 실제적으로는 agent마다 하나의 CPU core를 할당받는 병렬처리를 할 수 있습니다.
이전 소개에서 비동기 에이전트 라이브러리는 비동기 에이전트, 비동기 메세지 블록, 메세지 전달함수 3가지로 이루어진다고 하였습니다. 이 3가지 측면에서 예제를 살펴보겠습니다.

비동기 에이전트
agent를 상속받아 구현하면 됩니다. 예제에서처럼 하고자 하는 일을 상속받는 객체의 run함수를 재정의하여 사용하면 됩니다. start()함수를 호출하면 run함수가 실행됩니다. 하고자 하는 처리가 끝나면 done()을 호출하면 되고 외부에서는 쓰레드의 join() 함수처럼 run()함수가 끝나는 것을 agent::wait()함수를 통하여 기다리면 됩니다.

메세지 블록
에이전트들 간에 메세지를 주고 받는 채널이라고 보시면 됩니다. 여기서는 unbound_buffer와 overwrite_buffer를 이용하였습니다. 메세지를 주고 받는 메세지 블록은 무한히 메세지를 전달하냐 하나의 메세지를 계속 덮어써서 전달하냐 등 메세지 전달 형태에 따라 여러가지 클래스를 선택하여 사용할 수 있습니다.

메세지 전달함수
여기서는 블록API인 send, receive를 사용하여 메세지를 전달하였습니다. 참고로 비동기API들도 존재합니다.

 

반응형