From f620147fe6a3a0d447b843184a5b80afc754bd7f Mon Sep 17 00:00:00 2001 From: Klaus Basan Date: Tue, 19 Nov 2019 19:12:35 +0100 Subject: [PATCH] [FSD] Thread utility function to "call function in its own thread" --- src/blackmisc/threadutils.cpp | 16 ++++++++++++++++ src/blackmisc/threadutils.h | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/src/blackmisc/threadutils.cpp b/src/blackmisc/threadutils.cpp index 0e0b4578a..aee154f42 100644 --- a/src/blackmisc/threadutils.cpp +++ b/src/blackmisc/threadutils.cpp @@ -12,6 +12,8 @@ #include #include #include +#include +#include namespace BlackMisc { @@ -87,4 +89,18 @@ namespace BlackMisc { return threadInfo(QThread::currentThread()); } + + bool CThreadUtils::callInObjectThread(QObject *object, std::function callFunct) + { + if (!object) { return false; } + if (CThreadUtils::isCurrentThreadObjectThread(object)) { return false; } + + QPointer myself(object); + QTimer::singleShot(0, object, [ = ] + { + if (!myself) { return; } + callFunct(); + }); + return true; + } } // ns diff --git a/src/blackmisc/threadutils.h b/src/blackmisc/threadutils.h index f99fabf60..c0d5e5f0c 100644 --- a/src/blackmisc/threadutils.h +++ b/src/blackmisc/threadutils.h @@ -12,7 +12,9 @@ #define BLACKMISC_CTHREADUTILS_H #include "blackmisc/blackmiscexport.h" + #include +#include namespace BlackMisc { @@ -52,6 +54,9 @@ namespace BlackMisc //! Info about current thread static const QString currentThreadInfo(); + + //! Call in object's thread IF not already in object's thread + static bool callInObjectThread(QObject *object, std::function callFunct); }; } // ns