开发者

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. 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).

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.

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 e.g. foo::tick() and then let tick check to see if 60s has elapsed.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜