简体   繁体   English

C ++回调的线程安全计时器

[英]thread-safe timer for C++ callback

In a unix pthreads based app I'm working on, I have objects of a particular class (call it class foo) being created in multiple threads. 在我正在使用的基于UNIX pthreads的应用程序中,我具有在多个线程中创建的特定类(称为foo类)的对象。 I need a specific public method of class foo invoked at or after 60s of the object coming into existence (it is not imperative that it happens at precisely 60s, just that it happens at either 60s or very shortly thereafter). 我需要在对象出现后60 s或之后调用特定的foo类的公共方法(并不一定要在60 s时发生,只是在60 s或之后不久发生)。

Any ideas on what timers are available that could I use to achieve this? 关于可以使用哪些计时器的任何想法可以用来实现此目的? Looking for either something that I could just drop right in to my class foo or which I could derive from. 寻找我可以直接进入类foo或可以从中得到的东西。

The only real requirement is that it be thread-safe. 唯一真正的要求是它是线程安全的。

There are various platform specific mechanisms which will allow you to force an interruption of a thread at a given time, depending on various platform specific preconditions relating to the state of the thread. 有各种特定于平台的机制,这些机制将允许您在给定时间强制中断线程,具体取决于与线程状态有关的各种特定于平台的先决条件。 These are a bad idea unless you really need them and know why. 除非您确实需要它们并且知道原因,否则这不是一个好主意。

The correct solution, given the information in your question, would be to simply check elapsed time. 给定您问题中的信息,正确的解决方案是仅检查经过的时间。 Presumably these threads do some work in some sort of loop. 大概这些线程在某种循环中完成了一些工作。 As part of this loop, you should call eg foo::tick() and then let tick check to see if 60s has elapsed. 作为此循环的一部分,您应该调用例如foo :: tick(),然后让tick进行检查以查看是否已经过去了60秒钟。

Rather than using timer, why not define a static member within the class that is incremented in the constructor (with proper protection of course)? 而不是使用计时器,为什么不在类中定义一个在构造函数中递增的静态成员(当然要有适当的保护)? When the static member reaches 60, either invoke the member or flag that the condition has occurred and invoke elsewhere. 当静态成员达到60时,请调用该成员或标记该条件已发生,然后在其他位置调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM