Debian Codegraph @

im/pinyin/workerthread.h

raw symbols SCIP
1 /*
2 * SPDX-FileCopyrightText: 2024-2024 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 */
7 #ifndef _PINYIN_WORKERTHREAD_H_
8 #define _PINYIN_WORKERTHREAD_H_
9
10 #include <condition_variable>
11 #include <fcitx-utils/eventdispatcher.h>
12 #include <fcitx-utils/macros.h>
13 #include <fcitx-utils/trackableobject.h>
14 #include <functional>
15 #include <future>
16 #include <list>
17 #include <memory>
18 #include <mutex>
19 #include <queue>
20
21 class TaskToken : public fcitx::TrackableObject<TaskToken> {};
22
23 class WorkerThread {
24 public:
25 WorkerThread(fcitx::EventDispatcher &dispatcher);
26 ~WorkerThread();
27
28 template <typename Ret, typename OnDone>
29 FCITX_NODISCARD std::unique_ptr<TaskToken>
30 addTask(std::packaged_task<Ret()> task, OnDone onDone) {
31 // Wrap packaged_task and future in shared, since std::function require
32 // copy-able. The reason that we wrap it with in the std::function is
33 // because we need type erasure to store it.
34 std::shared_future<Ret> future = task.get_future();
35 std::function<void()> taskFunction =
36 [task = std::make_shared<decltype(task)>(
37 std::move(task))]() mutable { (*task)(); };
38 std::function<void()> callback =
39 [onDone = std::move(onDone), future = std::move(future)]() mutable {
40 onDone(future);
41 };
42
43 return addTaskImpl(std::move(taskFunction), std::move(callback));
44 }
45
46 private:
47 std::unique_ptr<TaskToken> addTaskImpl(std::function<void()> task,
48 std::function<void()> onDone);
49 static void runThread(WorkerThread *self) { self->run(); }
50 void run();
51
52 struct Task {
53 std::function<void()> task;
54 std::function<void()> callback;
55 fcitx::TrackableObjectReference<TaskToken> context;
56 };
57
58 fcitx::EventDispatcher &dispatcher_;
59 std::mutex mutex_;
60 std::queue<Task, std::list<Task>> queue_;
61 bool exit_ = false;
62 std::condition_variable condition_;
63
64 // Must be the last member, since we did not use a smart pointer to wrap it.
65 // The thread will be started right away at the end of constructor.
66 std::thread thread_;
67 };
68
69 #endif