-1

我需要一个计时器,所以你能告诉我如何制作一个每毫秒都会中断我的计时器,然后我会有一个变量来计算毫秒数,然后每 20 毫秒我会调用主要功能?

4

1 回答 1

0

如果没有其他事情可做,然后等待 20 毫秒,然后做一些事情,然后再次等待,以下方法可以:

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
  while (1)
  {
    struct timeval tv = {0, 20000}; /* 0 seconds, 20000 micro secs = 20 milli secs */

    if (-1 == select(0, NULL, NULL, NULL, &tv))
    {
      if (EINTR == errno)
      {
        continue; /* this means the process received a signal during waiting, just start over waiting. However this could lead to wait cycles >20ms and <40ms. */
      }

      perror("select()");
      exit(1);
    }

    /* do something every 20 ms */
  }

  return 0;
}
于 2013-06-28T06:49:12.330 回答