diff --git a/im/pinyin/workerthread.cpp b/im/pinyin/workerthread.cpp index c5a31ea..ceed63f 100644 --- a/im/pinyin/workerthread.cpp +++ b/im/pinyin/workerthread.cpp @@ -15,6 +15,8 @@ WorkerThread::WorkerThread(fcitx::EventDispatcher &dispatcher) : dispatcher_(dispatcher), thread_(&WorkerThread::runThread, this) {} WorkerThread::~WorkerThread() { + // Unlike other thread, there is no need to use a event loop since there is + // no IO monitoring, simply use exit_ to notify the exit. { std::lock_guard lock(mutex_); exit_ = true; @@ -28,6 +30,8 @@ WorkerThread::~WorkerThread() { std::unique_ptr WorkerThread::addTaskImpl(std::function task, std::function onDone) { + // Return an empty TrackableObject, so the unneeded task can be thrown away + // by simply delete TaskToken. auto token = std::make_unique(); std::lock_guard lock(mutex_); queue_.push({.task = std::move(task), @@ -50,7 +54,8 @@ void WorkerThread::run() { task = std::move(queue_.front()); queue_.pop(); } + // Run the actual task. task.task(); - dispatcher_.scheduleWithContext(task.context, std::move(task.callback)); + dispatcher_.scheduleWithContext(std::move(task.context), std::move(task.callback)); } -} \ No newline at end of file +} diff --git a/im/pinyin/workerthread.h b/im/pinyin/workerthread.h index 9b3871d..77f373f 100644 --- a/im/pinyin/workerthread.h +++ b/im/pinyin/workerthread.h @@ -28,14 +28,17 @@ class WorkerThread { template FCITX_NODISCARD std::unique_ptr addTask(std::packaged_task task, OnDone onDone) { - std::future future = task.get_future(); + // 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 = future.share()]() mutable { - onDone(future); - }; + std::function callback = + [onDone = std::move(onDone), future = std::move(future)]() mutable { + onDone(future); + }; return addTaskImpl(std::move(taskFunction), std::move(callback)); } @@ -58,8 +61,9 @@ class WorkerThread { bool exit_ = false; std::condition_variable condition_; - // Must be the last member + // 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 \ No newline at end of file +#endif