이번 튜토리얼에서는 C/C++에서 스레드(thread) 함수가 어떻게 동작하는지 예제 프로그램을 통해 살펴보겠습니다.
스레드 함수를 사용하면 여러 작업을 동시에(concurrently) 수행할 수 있습니다. 각 스레드는 서로 의존하며 실행할 수도 있고, 완전히 독립적으로 실행할 수도 있습니다.
C/C++ 스레드 프로그래밍의 핵심 함수
C 언어에서는 POSIX 스레드 라이브러리(pthread)를 사용해 멀티스레딩을 구현합니다. 이 예제에서 사용되는 주요 함수는 다음과 같습니다.
- pthread_create() : 새로운 스레드를 생성합니다.
- pthread_detach() : 현재 스레드를 분리(detach)하여, 종료 시 시스템이 자원을 자동으로 회수하도록 만듭니다.
- pthread_equal() : 두 스레드 ID가 동일한지 비교합니다.
- pthread_join() : 지정한 스레드가 종료될 때까지 호출한 스레드를 대기시킵니다.
- pthread_exit() : 현재 스레드의 실행을 종료합니다.
예제 코드
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* func(void* arg){
//현재 스레드 분리(detach)
pthread_detach(pthread_self());
printf("Inside the thread\n");
pthread_exit(NULL);
}
void fun(){
pthread_t ptid;
//새로운 스레드 생성
pthread_create(&ptid, NULL, &func, NULL);
printf("This line may be printed before thread terminates\n");
if(pthread_equal(ptid, pthread_self()))
printf("Threads are equal\n");
else
printf("Threads are not equal\n");
//생성된 스레드가 종료될 때까지 대기
pthread_join(ptid, NULL);
printf("This line will be printed" " after thread ends\n");
pthread_exit(NULL);
}
int main(){
fun();
return 0;
}
실행 결과
This line may be printed before thread terminates Threads are not equal Inside the thread This line will be printed after thread ends
코드 설명
fun() 함수가 호출되면 pthread_create()를 통해 새로운 스레드가 생성되고, func 함수가 해당 스레드에서 실행됩니다. 새 스레드는 곧바로 pthread_detach()로 자기 자신을 분리한 뒤 메시지를 출력하고 pthread_exit()로 종료됩니다.
한편 원래의 실행 흐름은 새 스레드의 종료를 기다리지 않고 다음 문장들을 계속 진행합니다. 그렇기 때문에 "This line may be printed before thread terminates"라는 문장이 스레드 종료보다 먼저 출력될 수 있습니다. 이후 pthread_equal()로 두 스레드 ID를 비교하면 서로 다른 스레드이므로 "Threads are not equal"이 출력됩니다.
마지막으로 pthread_join()은 생성된 스레드가 끝날 때까지 대기하는 역할을 하므로, "This line will be printed after thread ends"라는 문장은 반드시 스레드가 종료된 후에 출력됩니다.