기존 이솝 임베디드 포럼의 지식인 서비스가 게시판 형태로 변경되었습니다.
간단한 pthread 예제 인데요 제가 생각햇던거랑 결과가 다르게 나오는것 같아서 질문 드립니다.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
static int th_cnt = 0;
void *test_thread(void *arg){
int *pid = (int *)arg;
int id = *pid;
printf("thread %d start\n", id);
sleep(1000);
printf("thread %d end\n", id);
return NULL;
}
int main(int argc, char **argv){
int th_num = 5;
int i;
pthread_t th_test;
printf("MAIN start..\n");
printf("Thread start..\n");
for(i = 0; i < th_num; i++)
{
if(pthread_create(&th_test, NULL, test_thread, (void *)&i) != 0){
printf("thread %d create Fail..\n", i);
}
pthread_detach(th_test);
printf("-----pthread_detach end-----\n");
}
printf("MAIN end..\n");
return 0;
}
---------------------------------------------------------------
소스에서 pthread를 5개를 돌리면서 print를 이용해서 흐름과정을 출력하는데요
제가 생각한 결과는
MAIN start..
Thread start..
thread 0 start
thread 1start
thread 2start
thread 3start
thread 4start
thread 0end
thread 1end
thread 2end
thread 3end
thread 4end
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
이렇게 되리라 예상을 했는데요 물론 스레드 돌면서 위의 순서는 바뀌더라도 start, end, detach end 이 출력이 5쌍이
나오리라 생각을 했는데요
실행 결과는
# ./a.out
MAIN start..
Thread start..
-----pthread_detach end-----
-----pthread_detach end-----
thread 2 start
thread 2 start
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
MAIN end..
# ./a.out
MAIN start..
Thread start..
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
-----pthread_detach end-----
MAIN end..
두번 실행 했을때마다 start가 찍힐때도 있고 안찍힐때도 있는데요 end는 전혀 찍히지 않고 detach end는 5개는 잘 나옵니다
이게 왜 이렇게 나오는건가요?
detatch() 함수가 스레드 함수 종료될때까지 기다리고 메모리해제를 시키는 걸로 알고 있어서 저의 예상대로 나올지 알고 있었는데 실제로는 detach end가 start보다 먼저 출력이 되고 이러니 제가 잘 못 생각하고 있는것 같기도하구요;;
추가
pthread_join으로 하면 예상처럼 나오는데요 pthread_detach를 사용하면 왜 저렇게 나오는걸까요?
쭈암님 말씀대로.......
main이 끝나면 process가 종료된 것입니다.
즉, thread건 머건 없어지는 겁니다.
해서 pthread_join()이란 함수가 있어서 thread가 끝날때까지 기다려서 return을 처리해 주거나,
detach해서 에라......모르겠다....라고 할 경우는
while(1)
sleep(10);
이런 식으로 대기 모드로 들어가셔야 할겁니다.
detach는 내가 신경 안쓰겠다는 것입니다만, 끝나는 것을 기다려 주겠다라고 하는 것은 아닙니다.
즉, main이 끝나면.....나머지는 메롱입니다....
thread handler 하나를 가지고 5번 돌려쓰고 계시네요.
pthread_t th_test; -> pthread_t th_test[5];
pthread_create(&th_test, NULL, test_thread, (void *)&i) -> pthread_create(&th_test[i], NULL, test_thread, (void *)&i)
요렇게 해주심 되겠습니다.
요래도 잘 안되면, pthread_create 성공 이후에 usleep을 좀 줘보세요(100~1000 정도?)