在 Linux C 應用編程中,對于多線程編程中的定時器函數使用,通常可以借助?pthread
?庫和系統提供的定時器相關的函數來實現。
首先,常見的定時器函數有?setitimer()
?和?alarm()
?。setitimer()
?函數可以更精確地設置定時器,它可以設置為?ITIMER_REAL
(以實時時間遞減)、ITIMER_VIRTUAL
(以進程在用戶態執行的時間遞減)和?ITIMER_PROF
(以進程在用戶態和內核態執行的時間遞減)三種模式。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>#define TIMER_INTERVAL_SEC 2void timer_handler(union sigval sv)
{printf("Timer expired. Thread ID: %ld\n", pthread_self());
}void* thread_function(void* arg)
{timer_t timer_id;struct sigevent sev;sev.sigev_notify = SIGEV_THREAD;sev.sigev_notify_function = timer_handler;sev.sigev_value.sival_ptr = &timer_id;timer_create(CLOCK_REALTIME, &sev, &timer_id);struct itimerspec its;its.it_interval.tv_sec = TIMER_INTERVAL_SEC;its.it_interval.tv_nsec = 0;its.it_value.tv_sec = 1;its.it_value.tv_nsec = 0;timer_settime(timer_id, 0, &its, NULL);while (1) {sleep(1);}timer_delete(timer_id);pthread_exit(NULL);
}int main()
{pthread_t thread_id1, thread_id2;pthread_create(&thread_id1, NULL, thread_function, NULL);pthread_create(&thread_id2, NULL, thread_function, NULL);pthread_join(thread_id1, NULL);pthread_join(thread_id2, NULL);return 0;
}
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>#define TIMER_SIG SIGRTMINvoid timer_handler(int sig, siginfo_t *si, void *uc) {// 定時器到期時被調用的處理函數printf("Timer fired!\n");
}int main() {timer_t timerid;struct sigevent sev;struct itimerspec its;struct sigaction sa;// 設置處理函數sa.sa_flags = SA_SIGINFO;sa.sa_sigaction = timer_handler;sigemptyset(&sa.sa_mask);if (sigaction(TIMER_SIG, &sa, NULL) == -1) {perror("sigaction");exit(1);}// 創建定時器sev.sigev_notify = SIGEV_SIGNAL;sev.sigev_signo = TIMER_SIG;sev.sigev_value.sival_ptr = &timerid;if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {perror("timer_create");exit(1);}// 啟動定時器its.it_value.tv_sec = 2; // 初次到期時間,2秒后its.it_value.tv_nsec = 0;its.it_interval.tv_sec = 1; // 定時器周期,每隔1秒its.it_interval.tv_nsec = 0;if (timer_settime(timerid, 0, &its, NULL) == -1) {perror("timer_settime");exit(1);}sleep(10); // 等待定時器觸發幾次return 0;
}