#pragma once /* Copyright (c) 2016 Stanislaw Halik * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. */ #include "macros.hpp" #include #include #include #include #include #include namespace qt_impl_detail { template struct run_in_thread_traits { using ret_type = std::remove_reference_t; template static inline void assign(u& lvalue, t&& rvalue) { std::forward(lvalue) = std::forward(rvalue); } template static inline auto pass(t&& val) -> decltype(auto) { return std::forward(val); } template static inline auto call(F&& fun) -> decltype(auto) { return std::forward(fun)(); } }; template<> struct run_in_thread_traits { using type = unsigned char; using ret_type = void; static inline void assign(unsigned char&, unsigned char) {} static inline void pass(type) {} template static type call(F&& fun) { std::forward(fun)(); return type(0); } }; } template auto never_inline run_in_thread_sync(QObject* obj, F&& fun) -> typename qt_impl_detail::run_in_thread_traits::ret_type { using lock_guard = std::unique_lock; using traits = qt_impl_detail::run_in_thread_traits; typename traits::type ret; struct semaphore final { std::mutex mtx; std::condition_variable cvar; bool flag = false; semaphore() = default; void wait() { lock_guard guard(mtx); while (!flag) cvar.wait(guard); } void notify() { lock_guard guard(mtx); flag = true; cvar.notify_one(); } }; if (obj->thread() == QThread::currentThread()) return traits::pass(traits::call(fun)); semaphore sem; { QObject src; src.moveToThread(QThread::currentThread()); QObject::connect(&src, &QObject::destroyed, obj, [&] { traits::assign(ret, traits::call(fun)); sem.notify(); }, Qt::QueuedConnection); } sem.wait(); return traits::pass(std::move(ret)); } template void run_in_thread_async(QObject* obj, F&& fun) { if (obj->thread() == QThread::currentThread()) return (void)fun(); QObject src; QObject::connect(&src, &QObject::destroyed, obj, std::forward(fun), Qt::QueuedConnection); }