Add helper function for ensuring a function is run in the GUI thread (#4091)

This commit is contained in:
pajlada 2022-10-30 14:01:54 +01:00 committed by GitHub
parent d23d5c142e
commit e3af865a70
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 2 deletions

View file

@ -278,7 +278,10 @@ Image::~Image()
return; return;
} }
// run destructor of Frames in gui thread // Ensure the destructor for our frames is called in the GUI thread
// If the Image destructor is called outside of the GUI thread, move the
// ownership of the frames to the GUI thread, otherwise the frames will be
// destructed as part as we go out of scope
if (!isGuiThread()) if (!isGuiThread())
{ {
postToThread([frames = this->frames_.release()]() { postToThread([frames = this->frames_.release()]() {

View file

@ -1,7 +1,8 @@
#pragma once #pragma once
#include <QCoreApplication> #include "debug/AssertInGuiThread.hpp"
#include <QCoreApplication>
#include <QRunnable> #include <QRunnable>
#include <QThreadPool> #include <QThreadPool>
@ -29,6 +30,19 @@ private:
std::function<void()> action_; std::function<void()> action_;
}; };
template <typename F>
static void runInGuiThread(F &&fun)
{
if (isGuiThread())
{
fun();
}
else
{
postToThread(fun);
}
}
// Taken from // Taken from
// https://stackoverflow.com/questions/21646467/how-to-execute-a-functor-or-a-lambda-in-a-given-thread-in-qt-gcd-style // https://stackoverflow.com/questions/21646467/how-to-execute-a-functor-or-a-lambda-in-a-given-thread-in-qt-gcd-style
// Qt 5/4 - preferred, has least allocations // Qt 5/4 - preferred, has least allocations