티스토리 뷰

C C++/C++

Linux 환경에서의 pthread

개발하는꼬물이 2018. 2. 17. 17:44

** 컴파일 시 -lpthread 옵션을 꼭!! 붙여주어야 함 


1. 헤더파일

  - #include <pthread.h>



2. Pthread 함수

  1) pthread_create

    - int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

    - 새로운 쓰레드를 생성하는 함수 

    - thread : 생성된 쓰레드를 식별하기 위한 식별자 번호

    - attr : 생성되는 쓰레드의 특성을 지정하기 위해 사용. 기본 NULL

    - start_routine : 실제 쓰레드에서 실행될 쓰레드 함수

                      반환 값이 void* 타입이고 매개변수도 void* 로 선언된 함수만 가능 

                      ex) void* handler(void* arg) {..}

    - arg : 실행될 쓰레드 함수 start_routine에 넘길 함수 인자

            void형으로 넘겨주고 상황에 맞게 함수 내에서 형변환 캐스팅해서 사용하면 됨 

    - 성공적으로 생성되면 0 반환


  2) pthread_self

    - pthread_t pthread_self(void);

    - 해당 쓰레드의 쓰레드 번호(식별자)를 리턴하는 함수 


  3) pthread_join

    - int pthread_join(pthread_t th, void **thread_return);

    - 특정 쓰레드의 종료를 기다렸다가 종료 시 쓰레드의 종료값을 받아오고 쓰레드의 자원을 해제시켜줌

    - th : 조인하고자하는(어떤 쓰레드를 기다릴 지) 쓰레드의 식별자

    - thread_return : 쓰레드의 리턴값 (포인터로 값을 받아오는 점 주의!!)


  4) pthread_detach

    - int pthread_detach(pthread_t th);

    - main 쓰레드에서 pthread_create를 이용해 생성한 쓰레드를 분리시킴

    - 분리된 쓰레드는 종료할때 pthread_join을 기다리지 않고 모든 자원이 즉시 해제됨

    

  5) pthread_exit

    - void pthread_exit(void *retval);

    - 현재 실행중인 쓰레드를 종료함



3. 쓰레드 동기화 Pthread 함수

  1) pthread_lock

    - 잠금을 얻는 함수 

    - int pthread_lock(pthread_mutex_t *mutex);


  2) pthread_unlock

    - 잠금을 푸는 함수

    - int pthread_unlock(pthread_mutex_t *mutex);


  3) pthread_mutex_init

    - 뮤텍스 객체 초기화 함수

    - int pthread_mutex_init(pthred_mutex_t *mutex, const pthread_mutex_attr *attr);

    - mutex : 초기화 하려는 뮤텍스 객체 

    - attr : 뮤텍스 객체 mutex가 가질 수 있는 성질(fast<기본>, recursive, error checking)


  4) pthread_mutex_destroy

    - 뮤텍스 객체 제거 함수

    - int pthread_mutex_destroy(pthread_mutex_t *mutex);

    - mutex : 제거 하려는 뮤텍스 객체 



4. condition variable (조건변수)

  1) pthread_cond_wait()

    - condition variable을 기다리는 함수 

    - int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);

    - ex) pthread_cond_wait(&cond, &mutex);

    - wait 시 mutex_lock을 풀고 mutex를 다른 함수에게 넘겨줌.

    - signal을 받아 wait 상태에서 깨어날 때 다시 mutex를 잡아 lock을 검

  

  2) pthread_cond_signal()

    - wait중인 함수를 깨우는 함수

    - int pthread_cond_signal(pthread_cond_t *cond);

    - ex) pthread_cond_signal(&cond);

   

'C C++ > C++' 카테고리의 다른 글

[C++] 비트 구조체  (0) 2018.05.18
[C++] 난수 생성 - rand(), srand()  (0) 2018.05.04
[C++] SingleTon Pattern  (0) 2018.02.17
[C++] this  (0) 2018.02.17
[C++] \n과 \r의 차이  (0) 2017.12.06
댓글