#include "FunctionTransfer.h" #include #include Qt::HANDLE FunctionTransfer::gMainThreadId = nullptr; FunctionTransfer *FunctionTransfer::main_thread_forward = nullptr; Q_DECLARE_METATYPE(std::function) FunctionTransfer::FunctionTransfer(QObject *parent) : QObject(parent) { //ÒòΪstd::functionÊÇ×Ô¶¨ÒåµÄÀàÐÍ Òª¿çÏ̴߳«µÝÐèÒªÏÈ×¢²áһϠqRegisterMetaType>(); connect(this, SIGNAL(comming(std::function)), this, SLOT(slotExec(std::function)), Qt::BlockingQueuedConnection); connect(this, SIGNAL(comming_noBlock(std::function)), this, SLOT(slotExec(std::function)), Qt::QueuedConnection); } FunctionTransfer::~FunctionTransfer() { qDebug()<<__FUNCTION__; } void FunctionTransfer::init(Qt::HANDLE id) { gMainThreadId = id; FunctionTransfer::main_thread_forward = new FunctionTransfer(); } bool FunctionTransfer::isMainThread() { if (gMainThreadId == nullptr) { qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<"the main thread id is not set!"; return false; } if (QThread::currentThreadId() == gMainThreadId) { return true; } else { return false; } } void FunctionTransfer::runInMainThread(std::function f, bool isBlock) { // FunctionTransfer::main_thread_forward->exec(f, isBlock); if(FunctionTransfer::isMainThread()) { f(); } else { if (isBlock) { Q_EMIT FunctionTransfer::main_thread_forward->comming(f); } else { Q_EMIT FunctionTransfer::main_thread_forward->comming_noBlock(f); } } } void FunctionTransfer::slotExec(std::function f) { f(); // if(FunctionTransfer::isMainThread()) // { // f(); // } // else // { // if (isBlock) // { // Q_EMIT this->comming(f); // } // else // { // Q_EMIT this->comming_noBlock(f); // } // } }