1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#ifndef LOCKER_H
6#define LOCKER_H
7
8#include <mutex>
9#include <condition_variable>
10
11#include <QMessageBox>
12#include <QDebug>
13
14// Event provides a basic wait and signal synchronization primitive.
15class ConditionLock {
16 public:
17 // wait() blocks until the event is fired.
18 void wait()
19 {
20 std::unique_lock<std::mutex> lock(mutex);
21 cv.wait(lock, [&] { return fired; });
22 }
23
24 // fire() sets signals the event, and unblocks any calls to wait().
25 void fire()
26 {
27 std::unique_lock<std::mutex> lock(mutex);
28 fired = true;
29 cv.notify_all();
30 }
31
32 void reset()
33 {
34 fired = false;
35 }
36
37 private:
38 std::mutex mutex;
39 std::condition_variable cv;
40 bool fired = false;
41};
42
43class ConditionLockEx {
44 public:
45 // wait() blocks until the event is fired.
46 void wait(int seconds = 3)
47 {
48 std::unique_lock<std::mutex> lock(mutex);
49 if (cv.wait_for(lock, std::chrono::seconds(seconds)) == std::cv_status::timeout) {
50 qCritical() << "!!!Time Out!!!";
51 }
52 }
53
54 // fire() sets signals the event, and unblocks any calls to wait().
55 void fire()
56 {
57 std::unique_lock<std::mutex> lock(mutex);
58 cv.notify_all();
59 }
60
61 private:
62 std::mutex mutex;
63 std::condition_variable cv;
64};
65
66#endif // LOCKER_H
67