iVS3D v2.0.9
Loading...
Searching...
No Matches
asyncimageloader.h
1#pragma once
2#include <QObject>
3#include <QMutex>
4#include <QWaitCondition>
5#include <QThread>
6#include <functional>
7#include <optional>
8#include "opencv2/core.hpp"
9
10
12 uint idx;
13};
14Q_DECLARE_METATYPE(ImageRequest)
15
17 uint idx;
18 cv::Mat img;
19};
20Q_DECLARE_METATYPE(ImageResult)
21
22class AsyncImageLoader : public QObject
23{
24 Q_OBJECT
25public:
26 using WorkFunction = std::function<ImageResult(const ImageRequest&)>;
27
28 AsyncImageLoader(WorkFunction fn, QObject* parent = nullptr)
29 : QObject(parent), m_fn(fn)
30 {
31 static bool registered = false;
32 if (!registered) {
33 qRegisterMetaType<ImageRequest>("ImageRequest");
34 qRegisterMetaType<ImageResult>("ImageResult");
35 registered = true;
36 }
37 m_thread = new QThread(this);
38 connect(m_thread, &QThread::started, this, &AsyncImageLoader::processLoop);
39 this->moveToThread(m_thread);
40 m_thread->start();
41 }
42
44 {
45 QMutexLocker lock(&m_mutex);
46 m_quit = true;
47 m_wait.wakeAll();
48 }
49 m_thread->quit();
50 m_thread->wait();
51 }
52
53 // GUI thread calls this
54 void request(const ImageRequest& req) {
55 QMutexLocker lock(&m_mutex);
56 m_latestRequest = req;
57 m_hasNewRequest = true;
58 m_wait.wakeAll();
59 }
60
61signals:
62 void finished(const ImageRequest& req, const ImageResult& res);
63
64private slots:
65 void processLoop() {
66 while (true) {
67 ImageRequest work;
68
69 {
70 QMutexLocker lock(&m_mutex);
71 while (!m_hasNewRequest && !m_quit)
72 m_wait.wait(&m_mutex);
73
74 if (m_quit)
75 return;
76
77 // take the latest request, discard others
78 work = *m_latestRequest;
79 m_hasNewRequest = false;
80 }
81
82 // do work without holding the mutex
83 ImageResult result = m_fn(work);
84
85 emit finished(work, result);
86 }
87 }
88
89private:
90 WorkFunction m_fn;
91
92 QThread* m_thread;
93 QMutex m_mutex;
94 QWaitCondition m_wait;
95
96 std::optional<ImageRequest> m_latestRequest;
97 bool m_hasNewRequest = false;
98 bool m_quit = false;
99};
Definition asyncimageloader.h:23
Definition asyncimageloader.h:11
Definition asyncimageloader.h:16