简体   繁体   English

如何在 C++ 中安全地删除 posix 计时器?

[英]How do I safely delete a posix timer in c++?

The classes I'm writing contain posix timers and the handlers to those timers.我正在编写的类包含 posix 计时器和这些计时器的处理程序。

How do I safely delete the class?如何安全地删除课程? If the handlers fire and see that the class is deleted it segfaults.如果处理程序触发并看到该类被删除,则会出现段错误。

Adding a mutex leads to a deadlock - so I wondered if there was any resources about using posix timers in a c++ class safely in a multithreaded environment.添加互斥锁会导致死锁 - 所以我想知道是否有任何资源可以在多线程环境中安全地在 c++ 类中使用 posix 计时器。

Store the timer IDs as private members of your class, never return the ID, but always wrap calls that use them in your class' methods, and in your destructor, call timer_delete() ( http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_delete.html ). 将计时器ID存储为类的私有成员,从不返回ID,但始终将使用它们的调用包装在类的方法中,并在析构函数中timer_delete()http://pubs.opengroup.org/onlinepubs /9699919799/functions/timer_delete.html )。 This way, no code can hold a timer ID that has become invalid. 这样,任何代码都无法保存无效的计时器ID。 In short, Law of Demeter. 简而言之,得墨meter耳定律。

Your reference to deadlock implies that the problem is thread synchronization, so a shared_ptr might be the way to go. 您对死锁的引用意味着问题是线程同步,因此shared_ptr可能是解决之道。 This will delete the class object only when the last reference to it is deleted. 仅在删除最后一个对它的引用时,它才会删除该类对象。 You might try some other approach, such as synchronizing your threads behind a barrier or condition variable, and deleting only when you know that every thread holding a reference to the object is currently waiting, or a reader-writer lock. 您可以尝试其他方法,例如在屏障或条件变量后同步线程,并仅在知道每个持有对该对象引用的线程当前正在等待或读写器锁定时才删除。

According to the glibc maintainers , calling timer_settime() with a zero time will disarm the timer, letting you safely call timer_delete() .根据glibc 维护者的说法,使用零时间调用timer_settime()将解除计时器,让您安全地调用timer_delete() They say this ensures that no further callbacks will be forthcoming.他们说这确保不会有进一步的回调。

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

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