본문 바로가기
프로그래밍/C

C, Linux ] pthread 사용해 보기

by eteo 2022. 8. 25.

 

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

void *thread1_func (void *vargp)
{
        unsigned short cnt=0;

        printf("Thread 1 function starts...\n");

        while(1)
        {
                sleep(1);
                printf("thread1_func is running ===>(%d)\n", cnt++);
        }
}

void *thread2_func (void *vargp)
{
        unsigned short cnt=0;

        printf("Thread 2 function starts...\n");

        while(1)
        {
                sleep(3);
                printf("thread2_func is running =======> (%d)\n", cnt++);
        }
}

int main()
{

    char buf[32];

    pthread_t thread1ID, thread2ID;

    pthread_create(&thread1ID, NULL, thread1_func, (void *)&thread1ID);

    pthread_create(&thread2ID, NULL, thread2_func, (void *)&thread2ID);

    printf("\nType exit to terminate program !\n");

    while(1)
    {
            fgets(buf, sizeof(buf), stdin);
            if(strncmp(buf, "exit", 4)==0)
                break;
    }
    return 0;
}

 

 

쓰레드를 2개 생성하는데 main 포함 loop가 3개 돌고 있다. 쓰레드1은 1초에 한번씩 출력하고 쓰레드2는 3초에 한번씩 출력 하고 main 함수의 loop에서는 "exit" 입력을 대기한다.

참고로 리눅스의 sleep 함수는 초(s)단위 이다.

 

 

참고로 위의 케이스는 main 포함 쓰레드가 3개 돌고 있는데 main에 돌릴 내용이 없으면

while(1){
	sleep(1);
}

해도 되고 아니면

pthread_join(thread1ID, NULL);
pthread_join(thread2ID, NULL);

위처럼 pthread_join 함수를 쓰명 해당 쓰레드가 종료되는걸 기다리게 된다.

 

 

 

 

그리고 컴파일 시 다음과 같이 -lpthread 옵션을 주고 컴파일 해야한다.

 

gcc threadTest.c -o test -lpthread

 

이렇게하면 리눅스 공유 라이브러리 libpthread.so 를 참조하여 컴파일한다.

 

참고.

.a : 리눅스 정적 라이브러리

.so : 리눅스 동적 라이브러리

.lib : 윈도우 정적 라이브러리

.dll : 윈도우 동적 라이브러리