sliver__

[Mastering C++ Programming] - How to write a multithreaded application using the native C++ thread feature 본문

CS/C++

[Mastering C++ Programming] - How to write a multithreaded application using the native C++ thread feature

sliver__ 2022. 12. 8. 22:37
728x90
  • C++ 스레드 지원 라이브러리를 사용하여 다중 스레드 애플리케이션을 작성하는 것은 매우 간단합니다.
  • 스레드 클래스는 C++11에서 도입되었습니다. 
  • 이 함수는 스레드를 생성하는 데 사용할 수 있습니다. 
  • 이 함수와 동등한 기능은 POSIX pthread 라이브러리의 pthread_create입니다.
#include <thread>
using namespace std;
thread instance ( thread_procedure )

 

  • 인자는 아래와 같습니다

 

  • 이제 다음 코드에서 스레드 ID를 반환하는 인수는 아래와 같습니다.
this_thread::get_id ()
  • POSIX thread의 pthread_self() 와 같습니다.

 

thread::join()
  • join() 함수는 호출자 스레드 또는 기본 스레드를 차단하는 데 사용되므로 조인한 스레드가 작업을 완료할 때까지 대기합니다. 
  • 이것은 non-static 함수이므로 스레드 개체에서 호출해야 합니다.


  • 예제는 아래와 같습니다.
#include <thread>
#include <iostream>
using namespace std;

void threadProc() {
  for( int count=0; count<3; ++count ) {
    cout << "Message => "
         << count
         << " from "
         << this_thread::get_id()
         << endl;
  }
}

int main() {
  thread thread1 ( threadProc );
  thread thread2 ( threadProc );
  thread thread3 ( threadProc );

  thread1.join();
  thread2.join();
  thread3.join();

  return 0;
}
g++ main.cpp -std=c++17 -lpthread
728x90
Comments