멀티 쓰레드에서 하나의 쓰레드(A)는 Blocking 상태로 작업을 기다리고 있다고 할때, 또 다른 쓰레드(B)는 전체 프로그램의 상황을 모니터링하고 있다고 가정할때...
A는 Blocking 상태(Ex:사용자로부터 입력을 기다리고 있는 상태 - getc,scanf등..)일때, 쓰레드 B에서 현재 실행중인 프로그램을 종료해야 한다고 판단이 되면, 강제로 A쓰레드의 입력 대기 상태를 중단 시키고 쓰레드를 종료시키고자 할때...
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
static void *infinite_loop(void *arg)
{
char b[128];
do {
printf("wait for scanf()\n");
scanf("%s", &b[0]);
printf("done\n");
} while (1);
return (void*)(NULL);
}
static void control_cleanup(void *arg)
{
pthread_t *tids = arg;
printf("try to kill thread #0\n");
pthread_cancel(tids[0]);
}
static void *control(void *arg)
{
pthread_cleanup_push(control_cleanup, arg)
do {
pthread_testcancel();
} while (1);
pthread_cleanup_pop(1);
return (void*)(NULL);
}
int main(int argc, char **argv)
{
pthread_t tids[2];
int ret;
ret = pthread_create(&tids[0], NULL, infinite_loop, &tids[0]);
if (ret) {
perror("pthread_create()");
return EXIT_FAILURE;
}
ret = pthread_create(&tids[1], NULL, control, &tids[0]);
if (ret) {
perror("pthread_create()");
return EXIT_FAILURE;
}
sleep(5);
printf("try to kill thread #1\n");
pthread_cancel(tids[1]);
pthread_join(tids[0], (void**)NULL);
pthread_join(tids[1], (void**)NULL);
return EXIT_SUCCESS;
}



