我在互联网上找到了下面的代码,我试图了解 Linux 计时器是如何工作的,无论如何,正如您在 counter1 下方看到的那样,它是全局变量,如果 while 正在工作并且计时器关闭并更改会发生什么counter1 的值,我需要锁在那里吗?
// timertst1.c: Simple timer demo program. Use cross-gcc
// Vers. 1.00 - 21.Oct. 2002
// k.d.walter@t-online.de
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
// This is a timer handler.
int counter1 = 0;
void timerHandler (int signum)
{
printf ("timerHandler: counter= %d\n", counter1++);
fflush (stdout);
}
// This is the one and only main function.
int main (void)
{
struct sigaction sa;
struct itimerval timer;
// Install the timer handler...
memset (&sa, 0, sizeof (sa));
sa.sa_handler= &timerHandler;
sigaction (SIGALRM, &sa, NULL);
// Configure the timer to expire every 100 msec...
timer.it_value.tv_sec= 0; // First timeout
timer.it_value.tv_usec= 500000;
timer.it_interval.tv_sec= 0; // Interval
timer.it_interval.tv_usec= 500000;
// Start timer...
setitimer (ITIMER_REAL, &timer, NULL); setitimer (ITIMER_REAL, &timer, NULL);
// Do noting...
while (1) {
printf("i'm here waiting to be interuppted = %d\n",counter1);
//some work;
counter1++;
//some other work;
}
}