sliver__

[Mastering C++ Programming] - Asynchronous message passing 본문

CS/C++

[Mastering C++ Programming] - Asynchronous message passing

sliver__ 2022. 12. 9. 16:18
728x90
#include <iostream>
#include <future>
using namespace std;

void sayHello( promise<string> promise_ ) {
  promise_.set_value ( "Hello Concurrency support library!" );
}

int main ( ) {
  promise<string> promiseObj;

  future<string> futureObj = promiseObj.get_future( );
  async ( launch::async, sayHello, move( promiseObj ) );
  cout << futureObj.get( ) << endl;

  return 0;
}
  • promiseObj는 메인 스레드에 메시지를 비동기적으로 전달하기 위해 sayHello() 스레드 함수에 의해 사용되었습니다. 
  • promise<string>은 sayHello() 함수가 문자열 메시지를 전달할 것으로 예상되므로 기본 스레드가 future<string>을 검색함을 의미합니다. 
  • future::get() 함수 호출은 sayHello() 스레드 함수가 promise::set_value() 메서드를 호출할 때까지 차단됩니다.

  • 그러나 future::get() 메서드 호출에 대한 호출 후에 해당 약속 객체가 소멸되므로 future::get()은 한 번만 호출해야 한다는 점을 이해하는 것이 중요합니다.

  • std::move() 함수를 사용하는 것을 보셨나요? std::move() 함수는 기본적으로 promiseObj의 소유권을 sayHello() 스레드 함수로 이전하므로 std::move()가 호출된 후에는 메인 스레드에서 promiseObj에 액세스할 수 없습니다.2
728x90
Comments