목적
a와 b를 각각 무한히 출력하는 가장 기본적인 스레드 A와 B를 구현한다.
스레드 구현
헤더파일
#include <pthread.h> #include <stdio.h>
스레드 구현부
void *threadA()
{
while(1)
{
printf("a\n");
}
}
void *threadB()
{
while(1)
{
printf("b\n");
}
}
메인함수
pthread_create
// 리턴값 = pthread_create(스레드 아이디, 스레드 속성, 실행 함수, 스레드 함수 인자) int pthread_create( pthread_t *th_id, const pthread_attr_t *attr, void* 함수명, void *arg );
- 스레드 생성 함수
- pthread_create 함수의 리턴값이 0이면 성공, 아니면 실패다.
- 아래 예제에서는 스레드 속성과 스레드 함수 인자를 지정하지 않기 때문에 NULL로 둔다
pthread_join
// 리턴값 = pthread_join(스레드 아이디, 스레드 리턴 값) int pthread_join( pthread_t th_id, void** thread_return );
- 스레드 종료시 자원을 회수하는 함수
- pthread_join 함수의 리턴값이 0이면 성공, 아니면 실패다.
- prhead_create를 사용한 후 pthread_join, pthread_exit, pthread_detach와 같은 스레드 종료 함수를 호출하지 않을경우, 스레드 실행 중에 main이 종료되어 에러가 발생한다.
- 스레드 함수의 리턴값을 thread_return으로 받아올 수 있으나 아래 예제에서는 스레드 함수의 리턴값이 없기 때문에 NULL로 둔다.
int main()
{
pthread_t tA, tB; // 스레드 아이디
int threadErr = 0;
threadErr = pthread_create(&tA, NULL, threadA, NULL);
if(threadErr != 0)
{
printf("thread A create fail : %d\n", threadErr);
}
threadErr = pthread_create(&tB, NULL, threadB, NULL);
if(threadErr != 0)
{
printf("thread B create fail : %d\n", threadErr);
}
threadErr = pthread_join(tA, NULL);
if(threadErr != 0)
{
printf("thread A Join fail : %d\n", threadErr);
}
threadErr = pthread_join(tB, NULL);
if(threadErr != 0)
{
printf("thread B Join fail : %d\n", threadErr);
}
return 0;
}
전체 코드
#include <pthread.h>
#include <stdio.h>
void *threadA()
{
while(1)
{
printf("a\n");
}
}
void *threadB()
{
while(1)
{
printf("b\n");
}
}
int main()
{
pthread_t tA, tB;
int threadErr = 0;
threadErr = pthread_create(&tA, NULL, threadA, NULL);
if(threadErr != 0)
{
printf("thread A create fail : %d\n", threadErr);
}
threadErr = pthread_create(&tB, NULL, threadB, NULL);
if(threadErr != 0)
{
printf("thread B create fail : %d\n", threadErr);
}
threadErr = pthread_join(tA, NULL);
if(threadErr != 0)
{
printf("thread A Join fail : %d\n", threadErr);
}
threadErr = pthread_join(tB, NULL);
if(threadErr != 0)
{
printf("thread B Join fail : %d\n", threadErr);
}
return 0;
}