timer_create()와 SIGEV_THREAD 사용시 생성되는 thread관련
글쓴이: ertos12 / 작성시간: 화, 2022/03/08 - 4:59오후
timer_create()와 SIGEV_THREAD를 이용해서 아래와 같이 각각 5초와 10초 간격으로 실행되도록 thread를 만들과 실행했습니다. 그런데, 어떤 경우에 실행된 thread가 종료되지 않고, wait하고 있는 경우를 만들기 위해서, test2()에 1회 실행후 while(1)으로 loop를 실행했습니다. 원래 의도는 thread가 이미 실행되고 있다면, 다시 생성하지 않아야 할텐데, compile후 실행해 보면, 항상 새로운 thread가 생성됩니다. 이전에 생성한 thread가 아직 실행중이거나 종료되지 않았다면, 새로운 thread를 생성하지 않도록 할수는 없는지 문의 드립니다.
compile은 linux 환경에서 "gcc -Wall -lpthread -lrt -o tmtest tmtest.c"로 했습니다.
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include <signal.h> #include <pthread.h> static int frameNum[2] = {0, 0}; static const char *data1 = "THREAD1"; static const char *data2 = "THREAD2"; int create_timer(timer_t *timer_id, void (*func)(union sigval), int sec, int msec, char *data) { struct sigevent te; struct itimerspec its; // struct sigaction sa; int signo = SIGRTMIN; #if 0 sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = func; sigemptyset(&sa.sa_mask); if (sigaction(signo, &sa, NULL) == -1) { printf("sigaction error\n"); return -1; } #endif /* set and enable alarm */ te.sigev_notify = SIGEV_THREAD; te.sigev_signo = signo; // te.sigev_value.sival_int = sec; te.sigev_value.sival_ptr = (void *)data; te.sigev_notify_function = func; te.sigev_notify_attributes = NULL; timer_create(CLOCK_MONOTONIC, &te, timer_id); its.it_interval.tv_sec = sec; its.it_interval.tv_nsec = msec * 1000000; its.it_value.tv_sec = sec; its.it_value.tv_nsec = msec * 1000000; timer_settime(*timer_id, 0, &its, NULL); return 0; } void test1(union sigval parm) { time_t curTime = time(NULL); struct tm *plocal = localtime(&curTime); printf(">> TEST1(0x%lx) <<\n", pthread_self()); printf("parmp = %s\n", (char *)parm.sival_ptr); printf("localtime = %02d:%02d:%02d\n", plocal->tm_hour, plocal->tm_min, plocal->tm_sec); } void test2(union sigval parm) { time_t curTime = time(NULL); struct tm *plocal = localtime(&curTime); printf(">> TEST2(0x%lx) <<\n", pthread_self()); printf("2parms = %s\n", (char *)parm.sival_ptr); printf("2localtime = %02d:%02d:%02d\n", plocal->tm_hour, plocal->tm_min, plocal->tm_sec); // 1회 실행 후 test2 thread가 종료되지 않은 경우 test while(1) ; } int main (int argc, char *argv[]) { int i = 0; timer_t timerID[5]; printf("Hellow World on PC!\n"); create_timer(&timerID[0], test1, 5, 0, (char *)data1); create_timer(&timerID[1], test2, 10, 0, (char *)data2); while (1) { usleep(200); if (frameNum[0] >= 50) { for (i = 0; i < 5; i++) { if (timerID[i] != NULL) timer_delete(timerID[i]); } } } exit (0); }
Forums:
댓글 달기