결과를 보면 에러가 발생하는 것을 볼 수 있다.
참조사이트의 Thread Management > Joining Threads를 보면
It is impossible to join a detached thread (discussed next)
이라고 나온다.
즉, detached thread된 것은 join이 불가능하므로 pthread_join함수를 사용할 필요가 없다.
참고로 pthread_joinc은 waitpid와 비교될 수 있다.
pthread 예제4
쓰레드 생성후 쓰레드를 분리시키는 간단한 두번째 예제입니다.
pthread3.c에서 pthread_joinc에 관련된 코드를 삭제하였습니다.
pthread4 소스코드
#include <stdio.h>
#include <string.h>
#include <pthread.h>
pthread_t threads[5];
int done[5];
void *thread_main(void *);
int main(void)
{
int i;
int rc;
int status;
printf("pid=%d\n", getpid());
for (i = 0; i < 5; i++)
{
done[i] = 0;
pthread_create(&threads[i], NULL, &thread_main, (void *)i);
printf("%d, %d\n", i, threads[i]);
}
for (i = 4; i >= 0; i--)
{
done[i] = 1;
}
/* 쓰레드들이 실행하고 종료할 때 까지 잠시 기다린다.
sleep을 주지 않으면 메인이 종료되므로 자동으로 생성된 쓰레드도 강제종료되므로
올바른 테스트 진행되지 않아서 이다. */
sleep(5);
return 0;
}
void *thread_main(void *arg)
{
int i;
double result=0.0;
pthread_detach(pthread_self());
printf("therad: %d, %d\n", (int)arg, getpid());
while (!done[(int)arg])
{
for (i=0; i < 1000000; i++)
{
result = result + (double)random();
}
printf("thread: %d, result = %e\n", (int)arg, result);
}
printf("thread %d terminated....\n", (int)arg);
pthread_exit((void *) 0);
}
Contents
Posix Thread Example
pthread 예제1
pthread1.c 소스코드
pthread1 실행결과
pthread 예제2
pthread2.c 소스코드
pthread2 실행결과
pthread 예제3
pthread3.c 소스코드
pthread3 실행결과
pthread 예제4
pthread4 소스코드
pthread4 실행결과
참조사이트
Recent Posts
Archive Posts
Tags