본문 바로가기
개발 업무(코딩)-개발자였을때 썼던..

pthread에 관한 나만의 고찰

by 주용사 2023. 1. 8.
728x90

1. pthread_exit 를 한 후에는 printf등 함수가 안먹는다.

2. pthread_create 실행 라인에서 멈춰있지 않는다.

-> 함수를 다 실행하고 밑에 라인을 실행하는게 아니다. 그래서 sleep을 주는것이다(thread작업이 끝날때까지 기다려주는 것, pause사용해도돼). sub thread들이 끝날때까지 기다려주지 않고 main프로세스가 죽어버리면 thread는 자신의 기능을 다하지 못하고 죽어버린다.

3. pthread_join을 통해서 종료를 기다릴 수 있다

-> 데몬프로세스일때 스레드종료 후 프로세스 종료를 하지 않기 때문에 각각의 thread를 detach로 죽인다.(업무)

번외로 밑에 있는 소스 코드를 실행하기 위한 gcc

gcc -o a.out test.c -lpthread

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

static int global = 0;

void* do_loop(void *data)
{
        int i;


        int me = *((int *)data);
        printf("doloop in %x\n", pthread_self());

        //while(1)
        for(i = 0 ; i < 10 ; i++)
        {
                printf("%d global[%d]\n", me, ++global);

                //if(global == 10)
                //      break;
        }
#if (1)
        {
                pthread_detach (pthread_self());
                printf("[%d] doloop in %x\n", me, pthread_self());
                pthread_exit ((void *)NULL);
                printf("출력해도 안나와!!! %x\n", pthread_self());
        }
#endif

}

int main()
{
        int       thr_id;
        pthread_t p_thread[2];
        int status;
        int a = 0;
        int b = 1;

        pid_t pid = getpid();

        thr_id = pthread_create(&p_thread[0], NULL, do_loop, (void *)&a);
        thr_id = pthread_create(&p_thread[1], NULL, do_loop, (void *)&b);

        //pthread_join(p_thread[0], (void **) &status); // thread종료를 기다린다.
        //pthread_join(p_thread[1], (void **) &status);

        sleep(2);
        printf("main thread ..pthread_self %x, %d\n", pthread_self(), pid); // main thread
        printf("sub thread 11 ..p_pthread %x\n", p_thread[0]); // sub thread
        printf("sub thread 22..p_pthread %x\n", p_thread[1]); // sub thread

        printf("global[%d]\n", global);
        printf("programming is end\n");
        return 0;
}

728x90