安全跨线程信号/插槽C ++ [英] Safe Cross Thread Signals/Slot C++

查看:138
本文介绍了安全跨线程信号/插槽C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎唯一为信号类和插槽中提供安全跨线程信号的实现是QT. (也许我错了?).

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

但是我不能在我正在做的项目中使用QT.那么,如何从其他线程提供安全的Slot调用(例如,使用Boost :: signals2)?插槽内的互斥锁是唯一的方法吗?我认为signal2可以保护自己,但不能保护插槽内正在执行的操作.

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.

谢谢

推荐答案

您可以结合使用boost :: bind和boost ASIO来创建跨线程调用.

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

线程2将进入循环并执行您的绑定函数.我认为您也可以在此循环中调用Boost :: Signals2调用.

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)

我不太喜欢Boost :: Signals2,因为它的堆栈跟踪和编译时间非常长(

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

这篇关于安全跨线程信号/插槽C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆