File indexing completed on 2024-05-12 05:26:07

0001 /*
0002  * Copyright (C) 2014 Christian Mollekopf <chrigi_1@fastmail.fm>
0003  *
0004  * This library is free software; you can redistribute it and/or
0005  * modify it under the terms of the GNU Lesser General Public
0006  * License as published by the Free Software Foundation; either
0007  * version 2.1 of the License, or (at your option) version 3, or any
0008  * later version accepted by the membership of KDE e.V. (or its
0009  * successor approved by the membership of KDE e.V.), which shall
0010  * act as a proxy defined in Section 6 of version 3 of the license.
0011  *
0012  * This library is distributed in the hope that it will be useful,
0013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
0014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0015  * Lesser General Public License for more details.
0016  *
0017  * You should have received a copy of the GNU Lesser General Public
0018  * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
0019  */
0020 
0021 #include "threadboundary.h"
0022 #include <QThread>
0023 
0024 Q_DECLARE_METATYPE(std::function<void()>);
0025 
0026 namespace async {
0027 ThreadBoundary::ThreadBoundary() : QObject()
0028 {
0029     qRegisterMetaType<std::function<void()>>("std::function<void()>");
0030 }
0031 
0032 ThreadBoundary::~ThreadBoundary()
0033 {
0034 }
0035 
0036 void ThreadBoundary::callInMainThread(std::function<void()> f)
0037 {
0038     /*
0039      * This implementation causes lambdas to pile up if the target thread is the same as the caller thread, or the caller thread calls faster
0040      * than the target thread is able to execute the function calls. In that case any captures will equally pile up, resulting
0041      * in significant memory usage i.e. due to Emitter::addHandler calls that each capture a domain object.
0042      */
0043     if (QThread::currentThread() == this->thread()) {
0044         f();
0045     } else {
0046         QMetaObject::invokeMethod(this, "runInMainThread", Qt::QueuedConnection, QGenericReturnArgument(), Q_ARG(std::function<void()>, f));
0047     }
0048 }
0049 
0050 void ThreadBoundary::runInMainThread(std::function<void()> f)
0051 {
0052     f();
0053 }
0054 }