/* * SPDX-FileCopyrightText: 2024-2024 CSSlayer * * SPDX-License-Identifier: LGPL-2.1-or-later * */ #ifndef _PINYIN_WORKERTHREAD_H_ #define _PINYIN_WORKERTHREAD_H_ #include #include #include #include #include #include #include #include #include #include class TaskToken : public fcitx::TrackableObject {}; class WorkerThread { public: WorkerThread(fcitx::EventDispatcher &dispatcher); ~WorkerThread(); template FCITX_NODISCARD std::unique_ptr addTask(std::packaged_task task, OnDone onDone) { // Wrap packaged_task and future in shared, since std::function require // copy-able. The reason that we wrap it with in the std::function is // because we need type erasure to store it. std::shared_future future = task.get_future(); std::function taskFunction = [task = std::make_shared( std::move(task))]() mutable { (*task)(); }; std::function callback = [onDone = std::move(onDone), future = std::move(future)]() mutable { onDone(future); }; return addTaskImpl(std::move(taskFunction), std::move(callback)); } private: std::unique_ptr addTaskImpl(std::function task, std::function onDone); static void runThread(WorkerThread *self) { self->run(); } void run(); struct Task { std::function task; std::function callback; fcitx::TrackableObjectReference context; }; fcitx::EventDispatcher &dispatcher_; std::mutex mutex_; std::queue> queue_; bool exit_ = false; std::condition_variable condition_; // Must be the last member, since we did not use a smart pointer to wrap it. // The thread will be started right away at the end of constructor. std::thread thread_; }; #endif