sliver__

[Mastering C++ Programming] - Creating threads with the pthreads library 본문

CS/C++

[Mastering C++ Programming] - Creating threads with the pthreads library

sliver__ 2022. 12. 8. 22:20
728x90
  • thread 를 만드는 함수는 아래와 같다.
#include <pthread.h>
 int pthread_create(
              pthread_t *thread,
              const pthread_attr_t *attr,
              void *(*start_routine)(void*),
              void *arg
 )
  • argument는 아래와 같다.

 

 

 

 

  • 아래 함수는 코드에 표시된 것처럼 첫 번째 인수로 전달된 스레드가 종료될 때까지 호출자 스레드를 차단합니다.
int pthread_join ( pthread_t *thread, void **retval )
  • argument는 아래와 같습니다.

 

 

 

  • 아래 함수는 스레드 컨텍스트 내에서 사용해야 합니다. 
  • 여기서 retval은 이 함수를 호출한 스레드의 종료 코드를 나타내는 스레드의 종료 코드입니다.
int pthread_exit ( void *retval )
  • argument는 아래와 같습니다.

 

 

  • 아래 함수는 thread id를 return 한다.
pthread_t pthread_self(void)

 

 

  • 예제는 아래와 같습니다.
#include <pthread.h>
#include <iostream>

using namespace std;

void* threadProc ( void *param ) {
  for (int count=0; count<3; ++count)
    cout << "Message " << count << " from " << pthread_self()
         << endl;
  pthread_exit(0);
}

int main() {
  pthread_t thread1, thread2, thread3;

  pthread_create ( &thread1, NULL, threadProc, NULL );
  pthread_create ( &thread2, NULL, threadProc, NULL );
  pthread_create ( &thread3, NULL, threadProc, NULL );

  pthread_join( thread1, NULL );
  pthread_join( thread2, NULL );

  pthread_join( thread3, NULL );
  
  return 0;

}
g++ main.cpp -lpthread
  • lpthread dynamic library linking이 필요하다.

 

  • C++11부터 C++은 기본적으로 스레드를 지원하며 일반적으로 C++ 스레드 지원 라이브러리라고 합니다. 
  • C++ 스레드 지원 라이브러리는 POSIX pthreads C 라이브러리에 대한 추상화를 제공합니다. 
  • 시간이 지남에 따라 C++ 네이티브 스레드 지원이 크게 향상되었습니다.

  • pthread보다 C++ 네이티브 스레드를 사용하는 것이 좋습니다. 
  • C++ 스레드 지원 라이브러리는 Unix, Linux, macOS에서만 지원되고 Windows에서는 직접 지원되지 않는 POSIX pthread 라이브러리와 달리 공식적으로 표준 C++의 일부이므로 모든 플랫폼에서 지원됩니다.

  • 가장 좋은 부분은 스레드 지원이 C++17에서 새로운 수준으로 성숙했으며 C++20에서 다음 수준에 도달할 준비가 되어 있다는 것입니다. 따라서 프로젝트에서 C++ 스레드 지원 라이브러리를 사용하는 것을 고려하는 것이 좋습니다.
728x90
Comments