【问题标题】:Creating a simple timer application创建一个简单的计时器应用程序
【发布时间】:2010-06-21 08:49:54
【问题描述】:

gcc 4.4.3 vc++ 2008

我想让一个计时器应用程序在 windows 和 linux 上是可移植的。但是,开始就足够了。

我的想法是启动一个计时器并将其设置为指定的秒数。当时间到期时调用回调函数。

这是最好的方法吗?

非常感谢,

【问题讨论】:

  • 您所描述的听起来不像“应用程序”;这听起来像是编程接口 (API) 的一小部分。此外,您的问题文本奇怪地不完整,第二句话就停止了。我建议编辑它。
  • 你不能使用现有的库吗? "boost::asio::deadline_timer" 就是你要找的那个。
  • 使用提供此功能的库来隐藏操作系统之间的差异

标签: c windows linux


【解决方案1】:

有很多方法可以做一个计时器。这并不难,但你需要准确地思考你想要什么。如果要调用回调,通常在调用回调之前使用休眠的线程,直到延迟结束。如果你不想使用线程,你可以定期调用一个检查器函数来计算时间增量。

您的 api 将是一个带有延迟和函数指针以及回调参数的函数。它将启动一个休眠的线程,然后使用给定的参数调用回调。

检查通用库,它们通常实现了计时器(我认为是 gtk+ glib,boost::timer)。

my2c

编辑:

对于可移植性部分,您当然必须编写两个版本的计时器函数。如果您使用线程,则意味着最好使用库。由于库为您提供计时器...使用库:)

【讨论】:

    【解决方案2】:

    Windows 和 linux 使用不同的计时器。我建议您将计时功能封装到一个类中。您必须编写该类两次(每个平台一次),但程序的其余部分可以相同。

    或者,您可以使用其他人已经为您完成的工具包。例如QT 或 Boost。

    【讨论】:

      【解决方案3】:

      我曾在 C 和 C++ 中使用过几个这样的计时器。对于以下 url 上的 C GTK 示例,http://zetcode.com/tutorials/gtktutorial/gtkevents/ 可能会有所帮助。在 C++ 中,我使用了 glib 计时器 https://developer.gnome.org/glibmm/2.34/classGlib_1_1SignalTimeout.html(尽管它并不精确)。我还使用 libev(在 Linux 上使用 epoll(),在 Windows 上使用 select())以获得更好的精度计时器。对于C,我在下面给出一个例子

      //This program is demo for using pthreads with libev.
      //Try using Timeout values as large as 1.0 and as small as 0.000001
      //and notice the difference in the output
      
      //(c) 2013 enthusiasticgeek for stack overflow
      //Free to distribute and improve the code. Leave credits intact
      //On Ubuntu (assuming libev is installed) compile with the command - gcc -g test.c -o test -lev
      
      #include <ev.h>
      #include <stdio.h> // for printf
      #include <stdlib.h>
      
      double timeout = 1.0; //seconds
      ev_timer timeout_watcher;
      int timeout_count = 0;
      
      static void timeout_cb (EV_P_ ev_timer *w, int revents) // Timer callback function
      {   
          ++timeout_count;
          printf("%d\n", timeout_count);
          w->repeat = timeout;
          ev_timer_again(loop, &timeout_watcher); //Start the timer again.
      }
      
      int main (int argc, char** argv)
      {
          struct ev_loop *loop = EV_DEFAULT;  //or ev_default_loop (0);
          ev_timer_init (&timeout_watcher, timeout_cb, timeout, 0.); // Non repeating timer. The timer starts repeating in the timeout callback function
          ev_timer_start (loop, &timeout_watcher);
      
          // now wait for events to arrive
          ev_loop(loop, 0);
      
          return 0;
      }
      

      有关 libev 的更多文档,请查看 http://doc.dvgu.ru/devel/ev.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-09
        • 2014-11-18
        • 1970-01-01
        • 2012-04-30
        • 2016-12-16
        相关资源
        最近更新 更多