Qt实现指定线程执行回调

说明

  1. 同线程时,直接调用回调(block参数没意义)
  2. 创建invoker所在的线程,需要有Qt的消息循环(比如UI线程)

直接上代码

typedef std::function<void()> InvokerFunc;
class Invoker: public QObject
{
Q_OBJECT
public:
Invoker(QObject *parent=):
QObject(parent)
{
qRegisterMetaType<InvokerFunc>("InvokerFunc");
} void execute(const InvokerFunc &func, bool block)
{
if (QThread::currentThread()==thread())
{//is same thread
func();
return;
}
if (block)
{
metaObject()->invokeMethod(this, "onExecute", Qt::BlockingQueuedConnection,
Q_ARG(InvokerFunc, func));
}
else{
metaObject()->invokeMethod(this, "onExecute", Qt::QueuedConnection,
Q_ARG(InvokerFunc, func));
}
} private slots:
void onExecute(const InvokerFunc &func)
{
func();
}
};
上一篇:SSE图像算法优化系列四:图像转置的SSE优化(支持8位、24位、32位),提速4-6倍


下一篇:[置顶] iOS 应用程序内部国际化,不跟随系统语言