From: Steinar H. Gunderson Date: Thu, 20 Jul 2023 13:42:40 +0000 (+0200) Subject: Fix a threading issue, where we would call into the Qt thread from the video thread. X-Git-Url: https://git.sesse.net/?a=commitdiff_plain;h=1499d6f5c9c563843c5bba582d44a72c7cae27b2;p=pkanalytics Fix a threading issue, where we would call into the Qt thread from the video thread. --- diff --git a/post_to_main_thread.h b/post_to_main_thread.h new file mode 100644 index 0000000..080ed51 --- /dev/null +++ b/post_to_main_thread.h @@ -0,0 +1,27 @@ +#ifndef _POST_TO_MAIN_THREAD_H +#define _POST_TO_MAIN_THREAD_H 1 + +#include +#include +#include +#include + +// http://stackoverflow.com/questions/21646467/how-to-execute-a-functor-in-a-given-thread-in-qt-gcd-style +template +static inline void post_to_main_thread(F &&fun) +{ + QObject signalSource; + QObject::connect(&signalSource, &QObject::destroyed, qApp, std::move(fun)); +} + +template +static inline void post_to_main_thread_and_wait(F &&fun) +{ + std::promise done_promise; + std::future done = done_promise.get_future(); + post_to_main_thread(std::move(fun)); + post_to_main_thread([&done_promise] { done_promise.set_value(); }); + done.wait(); +} + +#endif // !defined(_POST_TO_MAIN_THREAD_H) diff --git a/video_widget.cpp b/video_widget.cpp index a5b4513..126e874 100644 --- a/video_widget.cpp +++ b/video_widget.cpp @@ -30,6 +30,8 @@ extern "C" { #include #include +#include "post_to_main_thread.h" + #include #include #include @@ -946,7 +948,9 @@ void VideoWidget::store_pts(int64_t pts) { last_pts = pts; last_position = lrint(pts * double(video_timebase.num) / double(video_timebase.den) * 1000); - emit position_changed(last_position); + post_to_main_thread([this, last_position{last_position.load()}] { + emit position_changed(last_position); + }); } // Taken from Movit (see the comment there for explanation)