Skip to content

Commit

Permalink
Improve comment in worker thread.
Browse files Browse the repository at this point in the history
  • Loading branch information
wengxt committed Apr 22, 2024
1 parent 737f00a commit f0322e0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
9 changes: 7 additions & 2 deletions im/pinyin/workerthread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::mutex> lock(mutex_);
exit_ = true;
Expand All @@ -28,6 +30,8 @@ WorkerThread::~WorkerThread() {
std::unique_ptr<TaskToken>
WorkerThread::addTaskImpl(std::function<void()> task,
std::function<void()> onDone) {
// Return an empty TrackableObject, so the unneeded task can be thrown away
// by simply delete TaskToken.
auto token = std::make_unique<TaskToken>();
std::lock_guard<std::mutex> lock(mutex_);
queue_.push({.task = std::move(task),
Expand All @@ -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));
}
}
}
18 changes: 11 additions & 7 deletions im/pinyin/workerthread.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,17 @@ class WorkerThread {
template <typename Ret, typename OnDone>
FCITX_NODISCARD std::unique_ptr<TaskToken>
addTask(std::packaged_task<Ret()> task, OnDone onDone) {
std::future<Ret> 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<Ret> future = task.get_future();
std::function<void()> taskFunction =
[task = std::make_shared<decltype(task)>(
std::move(task))]() mutable { (*task)(); };
std::function<void()> callback = [onDone = std::move(onDone),
future = future.share()]() mutable {
onDone(future);
};
std::function<void()> callback =
[onDone = std::move(onDone), future = std::move(future)]() mutable {
onDone(future);
};

return addTaskImpl(std::move(taskFunction), std::move(callback));
}
Expand All @@ -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
#endif

0 comments on commit f0322e0

Please sign in to comment.