Thread System 0.3.1
High-performance C++20 thread pool with work stealing and DAG scheduling
Loading...
Searching...
No Matches
thread_pool_sample.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2024, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
17#include <iostream>
18#include <memory>
19#include <chrono>
20
21#include "logger/core/logger.h"
24
26using namespace kcenon::thread;
27
28bool use_backup_ = false;
29uint32_t max_lines_ = 0;
30uint16_t wait_interval_ = 100;
31uint32_t test_line_count_ = 1000000;
32log_module::log_types file_target_ = log_module::log_types::None;
33log_module::log_types console_target_ = log_module::log_types::Information;
34log_module::log_types callback_target_ = log_module::log_types::None;
35
36uint16_t thread_counts_ = 10;
37
38auto initialize_logger() -> std::optional<std::string>
39{
40 log_module::set_title("thread_pool_sample");
41 log_module::set_use_backup(use_backup_);
42 log_module::set_max_lines(max_lines_);
43 log_module::file_target(file_target_);
44 log_module::console_target(console_target_);
45 log_module::callback_target(callback_target_);
46 // Note: This demonstrates the logger callback feature - std::cout is intentionally used here
47 log_module::message_callback(
48 [](const log_module::log_types& type, const std::string& datetime,
49 const std::string& message)
50 { std::cout << formatter::format("[{}][{}] {}\n", datetime, type, message); });
51 if (wait_interval_ > 0)
52 {
53 log_module::set_wake_interval(std::chrono::milliseconds(wait_interval_));
54 }
55
56 return log_module::start();
57}
58
59auto create_default(const uint16_t& worker_counts)
60 -> std::tuple<std::shared_ptr<thread_pool>, kcenon::common::VoidResult>
61{
62 std::shared_ptr<thread_pool> pool;
63
64 try
65 {
66 pool = std::make_shared<thread_pool>();
67 }
68 catch (const std::bad_alloc& e)
69 {
70 return { nullptr, kcenon::common::error_info{
71 kcenon::thread::error_code::allocation_failed,
72 e.what(),
73 "thread_pool_sample"} };
74 }
75
76 std::vector<std::unique_ptr<thread_worker>> workers;
77 workers.reserve(worker_counts);
78 for (uint16_t i = 0; i < worker_counts; ++i)
79 {
80 workers.push_back(std::make_unique<thread_worker>());
81 }
82
83 auto enqueue_result = pool->enqueue_batch(std::move(workers));
84 if (enqueue_result.is_err())
85 {
86 return { nullptr, enqueue_result.error() };
87 }
88
89 return { pool, kcenon::common::ok() };
90}
91
92auto store_job(std::shared_ptr<thread_pool> thread_pool) -> kcenon::common::VoidResult
93{
94 std::vector<std::unique_ptr<job>> jobs;
95 jobs.reserve(test_line_count_);
96
97 for (auto index = 0; index < test_line_count_; ++index)
98 {
99 jobs.push_back(std::make_unique<callback_job>(
100 [index](void) -> kcenon::common::VoidResult
101 {
102 log_module::write_debug("Hello, World!: {}", index);
103 return kcenon::common::ok();
104 }));
105 }
106
107 auto result = thread_pool->enqueue_batch(std::move(jobs));
108 if (result.is_err())
109 {
110 return result.error();
111 }
112
113 log_module::write_sequence("enqueued jobs: {}", test_line_count_);
114
115 return kcenon::common::ok();
116}
117
118auto main() -> int
119{
120 auto error_message = initialize_logger();
121 if (error_message.has_value())
122 {
123 std::cerr << formatter::format("error starting logger: {}\n",
124 error_message.value_or("unknown error"));
125 return 0;
126 }
127
128 std::shared_ptr<thread_pool> thread_pool = nullptr;
129 kcenon::common::VoidResult pool_init_result;
130 std::tie(thread_pool, pool_init_result) = create_default(thread_counts_);
131 if (pool_init_result.is_err())
132 {
133 log_module::write_error("error creating thread pool: {}",
134 pool_init_result.error().message);
135
136 return 0;
137 }
138
139 log_module::write_information("created {}", thread_pool->to_string());
140
141 auto store_result = store_job(thread_pool);
142 if (store_result.is_err())
143 {
144 log_module::write_error("error storing job: {}", store_result.error().message);
145
146 thread_pool.reset();
147
148 return 0;
149 }
150
151 auto start_result = thread_pool->start();
152 if (start_result.is_err())
153 {
154 log_module::write_error("error starting thread pool: {}",
155 start_result.error().message);
156
157 thread_pool.reset();
158
159 return 0;
160 }
161
162 log_module::write_information("started {}", thread_pool->to_string());
163
164 auto stop_result = thread_pool->stop();
165 if (stop_result.is_err())
166 {
167 log_module::write_error("error stopping thread pool: {}",
168 stop_result.error().message);
169 }
170
171 log_module::write_information("stopped {}", thread_pool->to_string());
172
173 thread_pool.reset();
174
175 log_module::stop();
176
177 return 0;
178}
A template class representing either a value or an error.
A thread pool for concurrent execution of jobs using multiple worker threads.
auto to_string(void) const -> std::string
Provides a string representation of this thread_pool.
auto enqueue_batch(std::vector< std::unique_ptr< job > > &&jobs) -> common::VoidResult
Enqueues a batch of jobs into the shared job_queue.
auto stop(const bool &immediately_stop=false) -> common::VoidResult
Stops the thread pool and all worker threads.
auto start(void) -> common::VoidResult
Starts the thread pool and all associated workers.
Provides convenience methods for string formatting using C++20 <format>.
Definition formatter.h:122
static auto format(const char *formats, const FormatArgs &... args) -> std::string
Formats a narrow-character string with the given arguments.
Definition formatter.h:132
Core thread pool implementation with work stealing and auto-scaling.
Generic formatter for enum types using user-provided converter functors.
Core threading foundation of the thread system library.
Definition thread_impl.h:17
log_module::log_types file_target_
auto store_job(std::shared_ptr< thread_pool > thread_pool) -> kcenon::common::VoidResult
log_module::log_types callback_target_
uint32_t max_lines_
bool use_backup_
auto main() -> int
auto initialize_logger() -> std::optional< std::string >
uint16_t thread_counts_
uint32_t test_line_count_
log_module::log_types console_target_
uint16_t wait_interval_
auto create_default(const uint16_t &worker_counts) -> std::tuple< std::shared_ptr< thread_pool >, kcenon::common::VoidResult >