From 76459d88bfd61139ad0e26d1a3b1333f32be12fa Mon Sep 17 00:00:00 2001 From: Michael M Date: Tue, 25 Jul 2017 20:46:35 -0700 Subject: [PATCH] QtUtils: add RunOnObject --- Source/Core/DolphinQt2/QtUtils/RunOnObject.h | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Source/Core/DolphinQt2/QtUtils/RunOnObject.h diff --git a/Source/Core/DolphinQt2/QtUtils/RunOnObject.h b/Source/Core/DolphinQt2/QtUtils/RunOnObject.h new file mode 100644 index 0000000000..9fbda0bbc1 --- /dev/null +++ b/Source/Core/DolphinQt2/QtUtils/RunOnObject.h @@ -0,0 +1,34 @@ +// Copyright 2017 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#pragma once + +#include +#include + +#include "Common/Event.h" +#include "DolphinQt2/QtUtils/QueueOnObject.h" + +class QObject; + +// QWidget and subclasses are not thread-safe! This helper takes arbitrary code from any thread, +// safely runs it on the appropriate GUI thread, waits for it to finish, and returns the result. + +template +auto RunOnObject(QObject* object, F&& functor) +{ + // If we queue up a functor on the current thread, it won't run until we return to the event loop, + // which means waiting for it to finish will never complete. Instead, run it immediately. + if (object->thread() == QThread::currentThread()) + return functor(); + + Common::Event event; + std::result_of_t result; + QueueOnObject(object, [&event, &result, functor = std::forward(functor) ] { + result = functor(); + event.Set(); + }); + event.Wait(); + return result; +}