Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어 pthread_cancel() 함수로 특정 스레드 취소하는 방법

pthread_cancel() 함수는 스레드 ID를 기반으로 특정 스레드를 취소할 때 사용됩니다. 이 함수는 대상 스레드에 취소 요청(cancellation request)을 전송하여 해당 스레드의 종료를 유도합니다.

함수 문법

int pthread_cancel(pthread_t th);

매개변수 th에는 취소하고자 하는 스레드의 ID가 전달됩니다. 함수 호출이 성공하면 0을 반환하고, 실패하면 오류 번호(error number)를 반환합니다.

그럼 실제 예제를 통해 이 함수로 스레드를 취소하는 방법을 살펴보겠습니다.

예제 코드

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>

int count = 0;
pthread_t sample_thread;

void* thread_one_func(void* p) {
    while (1) {
        printf("This is thread 1\n");
        sleep(1); // 1초 대기
        count++;
        if (count == 5) {
            // 카운터가 5가 되면 스레드 2에 취소 요청을 보내고 현재 스레드도 종료
            pthread_cancel(sample_thread);
            pthread_exit(NULL);
        }
    }
}

void* thread_two_func(void* p) {
    sample_thread = pthread_self(); // 스레드 2의 ID 저장
    while (1) {
        printf("This is thread 2\n");
        sleep(2); // 2초 대기
    }
}

main() {
    pthread_t t1, t2;
    // 두 개의 스레드 생성
    pthread_create(&t1, NULL, thread_one_func, NULL);
    pthread_create(&t2, NULL, thread_two_func, NULL);
    // 스레드 종료 대기
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
}

실행 결과

This is thread 2
This is thread 1
This is thread 1
This is thread 2
This is thread 1
This is thread 1
This is thread 1
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2

코드 설명

위 예제에서는 두 개의 스레드를 생성합니다. 첫 번째 스레드(thread_one_func)는 1초마다 메시지를 출력하며 카운터를 증가시키다가, 카운터가 5에 도달하면 pthread_cancel()을 호출해 두 번째 스레드에 취소 요청을 보낸 뒤 자신도 pthread_exit()로 종료됩니다.

두 번째 스레드(thread_two_func)는 pthread_self()로 자신의 스레드 ID를 전역 변수에 저장한 후 2초 간격으로 무한히 메시지를 출력합니다. 취소 요청을 받은 이후에는 더 이상 실행되지 않습니다.

주의 사항

스레드가 취소 요청을 받았다고 해서 반드시 즉시 종료되는 것은 아닙니다. 취소 요청은 해당 스레드가 취소 지점(cancellation point)에 도달했을 때 비로소 처리됩니다. sleep(), printf(), read() 등이 대표적인 취소 지점에 해당합니다. 또한 취소된 스레드는 PTHREAD_CANCELED 값으로 종료되므로, 다른 스레드가 pthread_join()을 통해 이 값을 확인하면 해당 스레드가 취소되었는지 판별할 수 있습니다.