/**
* @param pthread_t* thread 생성된 스레드의 ID값 저장
* @param pthread_attr_t* attr 스레드 속성 지정
* @param void*(*start_routine)(void *) 스레드 생성 시 실행
* @param void* arg start_routine의 매개변수
* @return int 0 or 에러넘버
*/
int phtread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
스레드 생성 함수
attr
이 널이면 디폴트 속성 사용
스레드 생성 후 attr
을 수정해도 스레드의 속성에는 영향 없음
성공적으로 생성한 경우 생성된 스레드의 ID를 thread 변수에 저장
start_routine(arg)
를 실행하면서 생성됨
start_routine
이 끝나면, pthread_exit(start_routine의 반환값)
을 암시적으로 호출하는 것과 동일한 효과(main()
을 호출한 스레드와 다름 -> main()
을 반환하면, exit(main의 반환값)
을 암시적으로 호출하는 것과 같음)
스레드가 종료될 때, 자원 회수 방법
thread_join()
을 호출하여 자원 회수pthread_detach()
를 호출하여 시스템이 회수생성된 스레드의 시그널 상태는 다음과 같이 초기화:
리턴값: 성공은 0, 실패는 에러 넘버
실패 사유
- [EAGAIN]: 자원 부족, 프로세스의 최대 스레드 수인 [PTHREAD_THREADS_MAX] 초과
- [EPERM]: 필요한 스케줄링 매개변수 또는 정책-을 설정할 수 있는 권한 없음
- [EINVAL]: The value specified by attr is invalid
/**
* @param pthread_t* thread 회수될 스레드
* @return int 0 or 에러넘버
*/
int pthread_detach(pthread_t thread);
스레드의 스토리지인 thread
는 스레드가 종료될 때 회수할 것임을 알림
리턴값: 성공 0 or 에러넘버
실패 사유
- [EINVAL]:
thread
에 의해 지정된 값이 joinable한 스레드를 참조하지 않을 경우- [ESRCH]:
thread
의 ID에 해당하는 스레드를 찾을 수 없음
/**
* @param pthread_t* thread 회수될 스레드
* @return int 0 or 에러넘버
*/
int pthread_join(pthread_t thread, void **valud_ptr);
대상 스레드가 종료될 때까지 호출 스레드 실행 일시 중지
널이 아닌 value_ptr 인수를 사용하여 pthread_join() 호출을 성공한 경우, 종료 스레드가 pthread_exit()에 전달한 값은 value_ptr에 저장
If the thread calling pthread_join() is cancelled, then the target thread is not detached.
리턴값: 성공 0 or 에러넘버
실패 사유
- [EINVAL]:
thread
에 의해 지정된 값이 joinable한 스레드를 참조하지 않을 경우- [ESRCH]:
thread
의 ID에 해당하는 스레드를 찾을 수 없음- [EDEADLK]: 교착 상태 발생 or
thread
가 호출 스레드일 경우
/**
* @param pthread_mutex_t* mutex
* @param pthread_mutexattr_t *attr
* @return int 0 or 에러넘버
*/
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
attr
에 명시된 속성을 가진 새로운 뮤텍스 생성(attr
== NULL -> 디폴트 속성)
성공: mutex
에 뮤텍스 아이디 저장, 0 리턴
실패: 에러 넘버 리턴
실패 사유
- [EINVAL]:
attr
의 값이 invalid- [ENOMEM]: 뮤텍스에 할당할 메모리 부족
/**
* @param pthread_mutex_t* mutex 대상 mutex
* @return int 0 or 에러넘버
*/
int pthread_mutex_destroy(pthread_mutex_t *mutex);
mutex
에 할당된 자원 해제
성공은 0, 실패는 에러 넘버 리턴
실패 사유
- [EINVAL]:
mutex
값이 invalid- [EBUSY]:
mutex
is locked
/**
* @param pthread_mutex_t* mutex 대상 mutex
* @return int 0 or 에러넘버
*/
int pthread_mutex_lock(pthread_mutex_t *mutex);
mutex
를 lock
If the mutex is already locked, the calling thread will block until the mutex becomes available.
성공은 0, 실패는 에러 넘버 리턴
실패 사유
- [EINVAL]:
mutex
값이 invalid- [EDEADLK]: 스레드가
mutex
를 기다릴 경우 데드락 발생 가능
/**
* @param pthread_mutex_t* mutex 대상 mutex
* @return int 0 or 에러넘버
*/
int pthread_mutex_lock(pthread_mutex_t *mutex);
If the current thread holds the lock on mutex, then the pthread_mutex_unlock() function unlocks mutex.
Calling pthread_mutex_unlock() with a mutex that the calling thread does not
hold will result in undefined behavior.
성공은 0, 실패는 에러 넘버 리턴
실패 사유
- [EINVAL]:
mutex
값이 invalid- [EPERM]: 현재 스레드가
mutex
lock x