Thread System 0.3.1
High-performance C++20 thread pool with work stealing and DAG scheduling
Loading...
Searching...
No Matches
main.cpp File Reference

Crash protection demonstration for thread system. More...

#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <vector>
#include <memory>
#include <atomic>
#include <kcenon/thread/interfaces/crash_handler.h>
#include <kcenon/thread/core/thread_pool.h>
#include <kcenon/thread/core/thread_worker.h>
#include <kcenon/thread/core/callback_job.h>
Include dependency graph for main.cpp:

Go to the source code of this file.

Classes

class  critical_resource
 

Functions

void simulate_segmentation_fault ()
 
void simulate_division_by_zero ()
 
void simulate_abort ()
 
void normal_task (int task_id)
 
void potentially_crashing_task (int task_id)
 
void on_system_crash (const crash_context &context)
 
void cleanup_global_resources ()
 
void emergency_state_save ()
 
int main ()
 

Variables

std::atomic< bool > system_running {true}
 
std::atomic< int > tasks_completed {0}
 
std::atomic< int > tasks_failed {0}
 
std::vector< std::shared_ptr< critical_resource > > global_resources
 

Detailed Description

Crash protection demonstration for thread system.

Definition in file main.cpp.

Function Documentation

◆ cleanup_global_resources()

void cleanup_global_resources ( )
Examples
crash_protection/main.cpp.

Definition at line 144 of file main.cpp.

144 {
145 std::cout << "[CLEANUP] Cleaning up global resources..." << std::endl;
146 for (auto& resource : global_resources) {
147 if (resource && resource->is_allocated()) {
148 resource->cleanup();
149 }
150 }
151 global_resources.clear();
152}
std::vector< std::shared_ptr< critical_resource > > global_resources
Definition main.cpp:66

References global_resources.

Referenced by main().

Here is the caller graph for this function:

◆ emergency_state_save()

void emergency_state_save ( )
Examples
crash_protection/main.cpp.

Definition at line 154 of file main.cpp.

154 {
155 std::cout << "[SAVE] Saving emergency state..." << std::endl;
156 std::cout << "Tasks completed: " << tasks_completed.load() << std::endl;
157 std::cout << "Tasks failed: " << tasks_failed.load() << std::endl;
158 std::cout << "Resources allocated: " << global_resources.size() << std::endl;
159}
std::atomic< int > tasks_completed
Definition main.cpp:36
std::atomic< int > tasks_failed
Definition main.cpp:37

References global_resources, tasks_completed, and tasks_failed.

Referenced by main().

Here is the caller graph for this function:

◆ main()

int main ( )

Definition at line 161 of file main.cpp.

161 {
162 std::cout << "=== Thread System Crash Protection Demo ===" << std::endl;
163 std::cout << "This demo shows comprehensive crash protection mechanisms\n" << std::endl;
164
165 // Step 1: Initialize crash protection
166 std::cout << "--- Step 1: Initialize Crash Protection ---" << std::endl;
167
169 crash_handler.initialize(crash_safety_level::standard, true);
171
172 // Register crash callbacks
173 auto crash_callback_id = crash_handler.register_crash_callback(
174 "SystemCrashHandler", on_system_crash, 10);
175
176 // Register cleanup functions
178 crash_handler.register_cleanup("EmergencyState", emergency_state_save, 1000);
179
180 std::cout << "[OK] Crash protection initialized" << std::endl;
181
182 // Step 2: Allocate critical resources
183 std::cout << "\n--- Step 2: Allocate Critical Resources ---" << std::endl;
184
185 global_resources.push_back(std::make_shared<critical_resource>("DatabaseConnection"));
186 global_resources.push_back(std::make_shared<critical_resource>("NetworkSocket"));
187 global_resources.push_back(std::make_shared<critical_resource>("FileHandle"));
188 global_resources.push_back(std::make_shared<critical_resource>("SharedMemory"));
189
190 // Step 3: Create and configure thread pool with crash protection
191 std::cout << "\n--- Step 3: Create Thread Pool ---" << std::endl;
192
193 using thread_pool_t = kcenon::thread::thread_pool;
194 using thread_worker_t = kcenon::thread::thread_worker;
196
197 auto thread_pool = std::make_shared<thread_pool_t>("MainPool");
198
199 // Enable crash protection for thread pool (conceptual)
202 [](const std::string& pool_name, const crash_context& context) {
203 std::cout << "[CRASH] Job crashed in pool: " << pool_name << std::endl;
204 std::cout << "Signal: " << context.signal_name << std::endl;
205 });
206
207 // Add workers
208 {
209 std::vector<std::unique_ptr<thread_worker_t>> workers;
210 for (int i = 0; i < 4; ++i) {
211 workers.push_back(std::make_unique<thread_worker_t>());
212 }
213 auto r = thread_pool->enqueue_batch(std::move(workers));
214 if (r.is_err()) {
215 std::cerr << "Failed to add workers: " << r.error().message << std::endl;
216 return 1;
217 }
218 }
219 // Start pool
220 {
221 auto r = thread_pool->start();
222 if (r.is_err()) {
223 std::cerr << "Failed to start thread pool: " << r.error().message << std::endl;
224 return 1;
225 }
226 }
227 std::cout << "[OK] Thread pool started with crash protection" << std::endl;
228
229 // Step 4: Submit normal tasks
230 std::cout << "\n--- Step 4: Submit Normal Tasks ---" << std::endl;
231
232 for (int i = 0; i < 10; ++i) {
233 auto job = std::make_unique<callback_job>(
234 [i]() -> kcenon::common::VoidResult {
235 normal_task(i);
236 return kcenon::common::ok();
237 }
238 );
239 auto r = thread_pool->enqueue(std::move(job));
240 if (r.is_err()) {
241 std::cerr << "enqueue normal task failed: " << r.error().message << std::endl;
242 }
243 }
244 // Give some time for tasks
245 std::this_thread::sleep_for(std::chrono::seconds(1));
246
247 std::cout << "[OK] All normal tasks completed" << std::endl;
248
249 // Step 5: Submit potentially crashing tasks
250 std::cout << "\n--- Step 5: Submit Potentially Crashing Tasks ---" << std::endl;
251 std::cout << "[WARN] Some of these tasks may crash - crash protection will handle them" << std::endl;
252
253 for (int i = 10; i < 25; ++i) {
254 auto job = std::make_unique<callback_job>(
255 [i, &crash_handler]() -> kcenon::common::VoidResult {
256 // Simulate occasional crash handling without real crash
257 std::random_device rd; std::mt19937 gen(rd());
258 std::uniform_int_distribution<> dist(1, 10);
259 int outcome = dist(gen);
260 if (outcome >= 9) {
261 crash_context ctx;
262 ctx.signal_number = SIGUSR1;
263 ctx.signal_name = "SIGUSR1";
264 ctx.fault_address = nullptr;
265 ctx.stack_trace = "Simulated crash";
266 ctx.crash_time = std::chrono::system_clock::now();
267 ctx.crashing_thread = std::this_thread::get_id();
269 tasks_failed.fetch_add(1);
270 } else {
271 std::this_thread::sleep_for(std::chrono::milliseconds(50));
272 tasks_completed.fetch_add(1);
273 }
274 return kcenon::common::ok();
275 }
276 );
277 auto r = thread_pool->enqueue(std::move(job));
278 if (r.is_err()) {
279 std::cerr << "enqueue risky task failed: " << r.error().message << std::endl;
280 }
281 }
282 std::this_thread::sleep_for(std::chrono::seconds(2));
283
284 // Step 6: Test manual crash scenarios
285 std::cout << "\n--- Step 6: Manual Crash Tests ---" << std::endl;
286
287 // Test 1: Manual crash trigger (for testing)
288 std::cout << "\nTest 1: Manual crash trigger" << std::endl;
289 crash_context test_context;
290 test_context.signal_number = SIGUSR1;
291 test_context.signal_name = "SIGUSR1";
292 test_context.fault_address = nullptr;
293 test_context.stack_trace = "Manual test stack trace";
294 test_context.crash_time = std::chrono::system_clock::now();
295 test_context.crashing_thread = std::this_thread::get_id();
296
298
299 // Test 2: Scoped crash protection
300 std::cout << "\nTest 2: Scoped crash protection" << std::endl;
301 {
302 scoped_crash_callback scoped_protection("ScopedTest",
303 [](const crash_context& ctx) {
304 std::cout << "[PROTECT] Scoped crash handler activated" << std::endl;
305 }, 50);
306
307 std::cout << "[OK] Scoped protection active" << std::endl;
308 // Scoped protection will be automatically removed when leaving this block
309 }
310 std::cout << "[OK] Scoped protection removed" << std::endl;
311
312 // Step 7: Display final statistics
313 std::cout << "\n--- Step 7: Final Statistics ---" << std::endl;
314
315 auto stats = crash_handler.get_stats();
316 std::cout << "Crash Statistics:" << std::endl;
317 std::cout << " Total crashes handled: " << stats.total_crashes_handled << std::endl;
318 std::cout << " Successful cleanups: " << stats.successful_cleanups << std::endl;
319 std::cout << " Failed cleanups: " << stats.failed_cleanups << std::endl;
320
321 std::cout << "\nTask Statistics:" << std::endl;
322 std::cout << " Tasks completed: " << tasks_completed.load() << std::endl;
323 std::cout << " Tasks failed: " << tasks_failed.load() << std::endl;
324
325 std::cout << "\nResource Status:" << std::endl;
326 for (const auto& resource : global_resources) {
327 std::cout << " " << resource->name() << ": "
328 << (resource->is_allocated() ? "allocated" : "cleaned up") << std::endl;
329 }
330
331 // Step 8: Graceful shutdown
332 std::cout << "\n--- Step 8: Graceful Shutdown ---" << std::endl;
333
334 std::cout << "Stopping thread pool..." << std::endl;
335 {
336 auto r = thread_pool->stop();
337 if (r.is_err()) {
338 std::cerr << "Failed to stop thread pool: " << r.error().message << std::endl;
339 }
340 }
341
342 std::cout << "Cleaning up resources..." << std::endl;
344
345 std::cout << "Unregistering crash callbacks..." << std::endl;
346 crash_handler.unregister_crash_callback(crash_callback_id);
347
348 std::cout << "\n=== Demo Completed Successfully ===" << std::endl;
349 std::cout << "Key features demonstrated:" << std::endl;
350 std::cout << "[OK] Signal handling and crash detection" << std::endl;
351 std::cout << "[OK] Stack trace generation" << std::endl;
352 std::cout << "[OK] Resource cleanup on crash" << std::endl;
353 std::cout << "[OK] Thread pool crash protection" << std::endl;
354 std::cout << "[OK] Scoped crash protection" << std::endl;
355 std::cout << "[OK] Graceful shutdown coordination" << std::endl;
356 std::cout << "[OK] Crash statistics and monitoring" << std::endl;
357
358 return 0;
359}
A specialized job class that encapsulates user-defined callbacks.
Thread-safe crash handler for the entire thread system.
void unregister_crash_callback(size_t registration_id)
Unregister a crash callback.
void initialize(crash_safety_level level=crash_safety_level::standard, bool enable_core_dumps=false)
Initialize crash handling with specified safety level.
void register_cleanup(const std::string &name, std::function< void()> cleanup, uint32_t timeout_ms=1000)
Register a resource cleanup function.
static crash_handler & instance()
Get the global crash handler instance.
crash_stats get_stats() const
size_t register_crash_callback(const std::string &name, crash_callback callback, int priority=100)
Register a callback to be called during crash handling.
void set_crash_log_directory(const std::string &directory)
Set custom crash log directory.
void trigger_crash_handling(const crash_context &context)
Manually trigger crash handling (for testing)
Represents a unit of work (task) to be executed, typically by a job queue.
Definition job.h:136
RAII helper for automatic crash callback registration.
static void set_job_crash_handler(std::function< void(const std::string &pool_name, const crash_context &)> handler)
Register job crash handler.
static void enable_for_pool(const std::string &pool_name, class thread_pool &pool)
Enable crash safety for a thread pool.
A thread pool for concurrent execution of jobs using multiple worker threads.
auto enqueue(std::unique_ptr< job > &&job) -> common::VoidResult
Enqueues a new job into the shared job_queue.
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.
A specialized worker thread that processes jobs from a job_queue.
void normal_task(int task_id)
Definition main.cpp:88
void on_system_crash(const crash_context &context)
Definition main.cpp:129
void emergency_state_save()
Definition main.cpp:154
void cleanup_global_resources()
Definition main.cpp:144
Crash context information.
std::chrono::system_clock::time_point crash_time

References cleanup_global_resources(), kcenon::thread::crash_context::crash_time, kcenon::thread::crash_context::crashing_thread, emergency_state_save(), kcenon::thread::thread_pool_crash_safety::enable_for_pool(), kcenon::thread::thread_pool::enqueue(), kcenon::thread::thread_pool::enqueue_batch(), kcenon::thread::crash_context::fault_address, kcenon::thread::crash_handler::get_stats(), global_resources, kcenon::thread::crash_handler::initialize(), kcenon::thread::crash_handler::instance(), normal_task(), on_system_crash(), kcenon::thread::crash_handler::register_cleanup(), kcenon::thread::crash_handler::register_crash_callback(), kcenon::thread::crash_handler::set_crash_log_directory(), kcenon::thread::thread_pool_crash_safety::set_job_crash_handler(), kcenon::thread::crash_context::signal_name, kcenon::thread::crash_context::signal_number, kcenon::thread::crash_context::stack_trace, kcenon::thread::thread_pool::start(), kcenon::thread::thread_pool::stop(), tasks_completed, tasks_failed, kcenon::thread::crash_handler::crash_stats::total_crashes_handled, kcenon::thread::crash_handler::trigger_crash_handling(), and kcenon::thread::crash_handler::unregister_crash_callback().

Here is the call graph for this function:

◆ normal_task()

void normal_task ( int task_id)
Examples
crash_protection/main.cpp.

Definition at line 88 of file main.cpp.

88 {
89 std::cout << "[TASK] Task " << task_id << " starting normally" << std::endl;
90
91 // Simulate some work
92 std::this_thread::sleep_for(std::chrono::milliseconds(100 + (task_id % 200)));
93
94 tasks_completed.fetch_add(1);
95 std::cout << "[TASK] Task " << task_id << " completed successfully" << std::endl;
96}

References tasks_completed.

Referenced by main().

Here is the caller graph for this function:

◆ on_system_crash()

void on_system_crash ( const crash_context & context)
Examples
crash_protection/main.cpp.

Definition at line 129 of file main.cpp.

129 {
130 std::cout << "\n[ALERT] CRASH DETECTED!" << std::endl;
131 std::cout << "Signal: " << context.signal_name << " (" << context.signal_number << ")" << std::endl;
132 std::cout << "Thread: " << context.crashing_thread << std::endl;
133 std::cout << "Time: " << std::chrono::duration_cast<std::chrono::seconds>(
134 context.crash_time.time_since_epoch()).count() << std::endl;
135
136 if (!context.stack_trace.empty()) {
137 std::cout << "Stack trace available" << std::endl;
138 }
139
140 // Mark system as no longer running
141 system_running.store(false);
142}
std::atomic< bool > system_running
Definition main.cpp:35

References kcenon::thread::crash_context::crash_time, kcenon::thread::crash_context::crashing_thread, kcenon::thread::crash_context::signal_name, kcenon::thread::crash_context::signal_number, kcenon::thread::crash_context::stack_trace, and system_running.

Referenced by main().

Here is the caller graph for this function:

◆ potentially_crashing_task()

void potentially_crashing_task ( int task_id)
Examples
crash_protection/main.cpp.

Definition at line 98 of file main.cpp.

98 {
99 std::cout << "[WARN] Task " << task_id << " starting (potentially dangerous)" << std::endl;
100
101 // Random chance of crash
102 std::random_device rd;
103 std::mt19937 gen(rd());
104 std::uniform_int_distribution<> crash_dist(1, 10);
105
106 int outcome = crash_dist(gen);
107
108 if (outcome <= 7) {
109 // Normal execution
110 std::this_thread::sleep_for(std::chrono::milliseconds(50));
111 tasks_completed.fetch_add(1);
112 std::cout << "[TASK] Task " << task_id << " completed safely" << std::endl;
113 } else if (outcome == 8) {
114 // Segmentation fault
115 tasks_failed.fetch_add(1);
117 } else if (outcome == 9) {
118 // Division by zero
119 tasks_failed.fetch_add(1);
121 } else {
122 // Abort
123 tasks_failed.fetch_add(1);
125 }
126}
void simulate_division_by_zero()
Definition main.cpp:75
void simulate_abort()
Definition main.cpp:82
void simulate_segmentation_fault()
Definition main.cpp:69

References simulate_abort(), simulate_division_by_zero(), simulate_segmentation_fault(), tasks_completed, and tasks_failed.

Here is the call graph for this function:

◆ simulate_abort()

void simulate_abort ( )
Examples
crash_protection/main.cpp.

Definition at line 82 of file main.cpp.

82 {
83 std::cout << "[CRASH] Simulating abort..." << std::endl;
84 std::abort(); // This will cause SIGABRT
85}

Referenced by potentially_crashing_task().

Here is the caller graph for this function:

◆ simulate_division_by_zero()

void simulate_division_by_zero ( )
Examples
crash_protection/main.cpp.

Definition at line 75 of file main.cpp.

75 {
76 std::cout << "[CRASH] Simulating division by zero..." << std::endl;
77 volatile int zero = 0;
78 volatile int result = 100 / zero; // This will cause SIGFPE
79 (void)result;
80}
A template class representing either a value or an error.

Referenced by potentially_crashing_task().

Here is the caller graph for this function:

◆ simulate_segmentation_fault()

void simulate_segmentation_fault ( )
Examples
crash_protection/main.cpp.

Definition at line 69 of file main.cpp.

69 {
70 std::cout << "[CRASH] Simulating segmentation fault..." << std::endl;
71 int* null_ptr = nullptr;
72 *null_ptr = 42; // This will cause SIGSEGV
73}

Referenced by potentially_crashing_task().

Here is the caller graph for this function:

Variable Documentation

◆ global_resources

std::vector<std::shared_ptr<critical_resource> > global_resources
Examples
crash_protection/main.cpp.

Definition at line 66 of file main.cpp.

Referenced by cleanup_global_resources(), emergency_state_save(), and main().

◆ system_running

std::atomic<bool> system_running {true}
Examples
crash_protection/main.cpp, and typed_job_queue_sample.cpp.

Definition at line 35 of file main.cpp.

35{true};

Referenced by on_system_crash(), and task_scheduling_example().

◆ tasks_completed

std::atomic<int> tasks_completed {0}
Examples
crash_protection/main.cpp.

Definition at line 36 of file main.cpp.

36{0};

Referenced by emergency_state_save(), main(), normal_task(), and potentially_crashing_task().

◆ tasks_failed

std::atomic<int> tasks_failed {0}
Examples
crash_protection/main.cpp.

Definition at line 37 of file main.cpp.

37{0};

Referenced by emergency_state_save(), main(), and potentially_crashing_task().