FTXUI 6.1.9
C++ functional terminal UI.
Loading...
Searching...
No Matches
task_runner.cpp
Go to the documentation of this file.
1// Copyright 2024 Arthur Sonzogni. All rights reserved.
2// Use of this source code is governed by the MIT license that can be found in
3// the LICENSE file.
5
6#include <cassert>
7#include <thread>
8
9namespace ftxui::task {
10
11static thread_local TaskRunner* current_task_runner = nullptr; // NOLINT
12
14 assert(!previous_task_runner_);
15 previous_task_runner_ = current_task_runner;
16 current_task_runner = this;
17}
18
20 current_task_runner = previous_task_runner_;
21}
22
23// static
25 assert(current_task_runner);
26 return current_task_runner;
27}
28
29auto TaskRunner::PostTask(Task task) -> void {
30 queue_.PostTask(PendingTask{std::move(task)});
31}
32
34 std::chrono::steady_clock::duration duration)
35 -> void {
36 queue_.PostTask(PendingTask{std::move(task), duration});
37}
38
39/// Runs the tasks in the queue.
41 -> std::optional<std::chrono::steady_clock::duration> {
42 while (true) {
43 auto maybe_task = queue_.Get();
44 if (std::holds_alternative<std::monostate>(maybe_task)) {
45 // No more tasks to execute, exit the loop.
46 return std::nullopt;
47 }
48
49 if (std::holds_alternative<Task>(maybe_task)) {
50 executed_tasks_++;
51 std::get<Task>(maybe_task)();
52 continue;
53 }
54
55 if (std::holds_alternative<std::chrono::steady_clock::duration>(
56 maybe_task)) {
57 return std::get<std::chrono::steady_clock::duration>(maybe_task);
58 }
59 }
60}
61
62auto TaskRunner::Run() -> void {
63 while (true) {
64 auto duration = RunUntilIdle();
65 if (!duration) {
66 // No more tasks to execute, exit the loop.
67 return;
68 }
69
70 // Sleep for the duration until the next task can be executed.
71 std::this_thread::sleep_for(duration.value());
72 }
73}
74
75} // namespace ftxui::task
static auto Current() -> TaskRunner *
auto PostTask(Task task) -> void
Schedules a task to be executed immediately.
auto RunUntilIdle() -> std::optional< std::chrono::steady_clock::duration >
Runs the tasks in the queue.
auto PostDelayedTask(Task task, std::chrono::steady_clock::duration duration) -> void
Schedules a task to be executed after a certain duration.
std::function< void()> Task
A task represents a unit of work.