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
24// static
26 assert(current_task_runner);
27 return current_task_runner;
28}
29
30auto TaskRunner::PostTask(Task task) -> void {
31 queue_.PostTask(PendingTask{std::move(task)});
32}
33
35 std::chrono::steady_clock::duration duration)
36 -> void {
37 queue_.PostTask(PendingTask{std::move(task), duration});
38}
39
40/// Runs the tasks in the queue.
42 -> std::optional<std::chrono::steady_clock::duration> {
43 while (true) {
44 auto maybe_task = queue_.Get();
45 if (std::holds_alternative<std::monostate>(maybe_task)) {
46 // No more tasks to execute, exit the loop.
47 return std::nullopt;
48 }
49
50 if (std::holds_alternative<Task>(maybe_task)) {
51 executed_tasks_++;
52 std::get<Task>(maybe_task)();
53 continue;
54 }
55
56 if (std::holds_alternative<std::chrono::steady_clock::duration>(
57 maybe_task)) {
58 return std::get<std::chrono::steady_clock::duration>(maybe_task);
59 }
60 }
61}
62
63auto TaskRunner::Run() -> void {
64 while (true) {
65 auto duration = RunUntilIdle();
66 if (!duration) {
67 // No more tasks to execute, exit the loop.
68 return;
69 }
70
71 // Sleep for the duration until the next task can be executed.
72 std::this_thread::sleep_for(duration.value());
73 }
74}
75
76} // namespace ftxui::task
77
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.