| 1 | /* |
| 2 | * SPDX-FileCopyrightText: 2024-2024 CSSlayer <[email protected]> |
| 3 | * |
| 4 | * SPDX-License-Identifier: LGPL-2.1-or-later |
| 5 | * |
| 6 | */ |
| 7 | #include "workerthread.h" |
| 8 | #include <condition_variable> |
| 9 | #include <fcitx-utils/eventdispatcher.h> |
| 10 | #include <memory> |
| 11 | #include <mutex> |
| 12 | #include <thread> |
| 13 | |
| 14 | WorkerThread::WorkerThread(fcitx::EventDispatcher &dispatcher) |
| 15 | : dispatcher_(dispatcher), thread_(&WorkerThread::runThread, this) {} |
| 16 | |
| 17 | WorkerThread::~WorkerThread() { |
| 18 | // Unlike other thread, there is no need to use a event loop since there is |
| 19 | // no IO monitoring, simply use exit_ to notify the exit. |
| 20 | { |
| 21 | std::lock_guard<std::mutex> lock(mutex_); |
| 22 | exit_ = true; |
| 23 | condition_.notify_one(); |
| 24 | } |
| 25 | if (thread_.joinable()) { |
| 26 | thread_.join(); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | std::unique_ptr<TaskToken> |
| 31 | WorkerThread::addTaskImpl(std::function<void()> task, |
| 32 | std::function<void()> onDone) { |
| 33 | // Return an empty TrackableObject, so the unneeded task can be thrown away |
| 34 | // by simply delete TaskToken. |
| 35 | auto token = std::make_unique<TaskToken>(); |
| 36 | std::lock_guard<std::mutex> lock(mutex_); |
| 37 | queue_.push({.task = std::move(task), |
| 38 | .callback = std::move(onDone), |
| 39 | .context = token->watch()}); |
| 40 | condition_.notify_one(); |
| 41 | return token; |
| 42 | } |
| 43 | |
| 44 | void WorkerThread::run() { |
| 45 | while (true) { |
| 46 | Task task; |
| 47 | { |
| 48 | std::unique_lock lock(mutex_); |
| 49 | condition_.wait(lock, [this] { return exit_ || !queue_.empty(); }); |
| 50 | if (exit_) { |
| 51 | break; |
| 52 | } |
| 53 | |
| 54 | task = std::move(queue_.front()); |
| 55 | queue_.pop(); |
| 56 | } |
| 57 | // Run the actual task. |
| 58 | task.task(); |
| 59 | dispatcher_.scheduleWithContext(std::move(task.context), |
| 60 | std::move(task.callback)); |
| 61 | } |
| 62 | } |