Safe Cross Thread Signals/Slot C++

房东的猫 提交于 2020-05-15 05:08:46

问题


It seem that the only implementation that provide Safe Cross-Thread Signals for both the Signal class and what's being called in the slot is QT. (Maybe I'm wrong?).

But I cannot use QT in the project I'm doing. So how could I provide safe Slots call from a different thread (Using Boost::signals2 for example)? Are mutex inside the slot the only way? I think signals2 protect themself but not what's being done inside the slot.

Thanks


回答1:


You can combine boost::bind and boost ASIO to create Cross-Thread Calls.

# In Thread 2
boost::asio::io_service service;
boost::asio::io_service::work work (service); // so io service won't stop if there is no work 
service.run() # starting work thread

# In Thread 1
service.post (boost::bind (&YourClass::function, &yourClassInstance, parameter1, parameter2))

Thread 2 will go into a loop and will execute your bound function. I think you can also call Boost::Signals2 calls into this loop.

But keep care: If you do cross-thread-signaling, make sure that the destination object still exists when being called. You can garantuee that by dropping all connections in your targets destructor (not in their base class destructor, also see Signals-Trackable Class)

I do not like Boost::Signals2 oo much, because of its very long stack trace and compile times (blog post).




回答2:


It's not a signals-slots implementation, exactly, but there's a C++ implementation of Twisted's Deferred pattern that accomplishes a similar goal to a cross-thread signal-slot mechanism. If someone doesn't come along and post a better solution, it might be worth a look: http://sourceforge.net/projects/deferred/



来源:https://stackoverflow.com/questions/2757937/safe-cross-thread-signals-slot-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!