使用 select 实现定时器

发布于 2024-09-14 22:29:28 字数 461 浏览 1 评论 0原文

我计划使用 timerfd_create 用 C 语言编写一个小型计时器库。

该库的基本用户将有两个线程

  • 应用程序线程
  • 计时器线程

这两个线程之间将有一个队列,以便每当应用程序想要启动计时器时,它将向队列中推送一条消息,然后计时器线程将读取该消息并发送消息。为其创建一个FD并将其放入select中。

上述方法的问题在于,作为单个线程的计时器线程将在 select 系统调用中被阻塞,并且不知道是否已将消息发布到其接收队列中以启动计时器。

解决这个问题的一种方法是让选择在每个“滴答声”超时,然后检查队列中的消息。他们有更好的方法吗? 我还考虑在每次应用程序将消息放入 select 队列中时引发中断以中断 select。这适用于多线程应用程序吗?

平台:Unix

I am planning to write a small timer library in C using timerfd_create.

The basic user of this library will have two threads

  • application thread
  • Timer thread

There will be a queue between these two threads so that whenever the application wants to start a timer, it will push a message into the queue which the timer thread will then read and create an FD for it and put it in select.

The problem with the above approach is that the timer thread being a single thread would be blocked in the select system call and would not know if a message has been posted in his receive queue to start a timer.

One way around this is to let the select timeout every "tick" and then check for messages in the queue. Is their a better way to do this?
I was also thinking of raising an Interrupt every time the application puts a message in the select queue to interrupt the select. Does that work well with Multi-threaded applications?

Platform : Unix

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

玉环 2024-09-21 22:29:28

如果您坚持让多个线程将计时器发送到 select(2) 中的专用计时器线程,那么为什么不使用 eventfd(2) 或者只是一个老式的 自管道技巧 表示新计时器可用。将事件文件描述符包含到可轮询集中,等待所有事件文件描述符。

If you insist on having multiple threads post timers to a dedicated timer thread sitting in select(2), then why not use eventfd(2) or just an old-good self-pipe trick to signal that new timers are available. Include the event file descriptor to the pollable set, wait on all of them.

迟到的我 2024-09-21 22:29:28

您想要定位哪些平台?例如,在 Windows 下,有很多更好的方法可以在不使用 select() 的情况下处理此问题,例如 PostThreadMessage() 和 WaitMessage()。

Which platform(s) are you wanting to target? Under Windows, for instance, there are much better ways to handle this without using select(), such as PostThreadMessage() and WaitMessage().

ゝ杯具 2024-09-21 22:29:28

如果您使用的是timerfd,则不需要专用的计时器线程,只需使用selectpollepoll围绕事件循环编写应用程序即可代码>等

If you are using timerfd's then there is no need for a dedicated timer thread, just write the application around an event loop using select, poll, or epoll, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文