CCF
Loading...
Searching...
No Matches
worker.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
6#include "tasks/job_board.h"
7
8#include <atomic>
9#include <chrono>
10#include <cstdlib>
11#include <exception>
12#include <string>
13
14namespace ccf::tasks
15{
16 // Logs the error message and a demangled throw-point stacktrace when
17 // available.
18 void dump_stacktrace(const std::string& msg);
19
20 // Executes a task with exception handling. On any exception, logs a
21 // stacktrace and aborts (unless abort_on_throw is false).
22 inline void try_do_task(BaseTask& task, bool abort_on_throw = true)
23 {
24 if (task.is_cancelled())
25 {
26 return;
27 }
28
29 try
30 {
31 task.do_task();
32 }
33 catch (const std::exception& e)
34 {
35 dump_stacktrace(fmt::format(
36 "{} task failed with exception: {}", task.get_name(), e.what()));
37 if (abort_on_throw)
38 {
39 std::abort();
40 }
41 }
42 catch (...)
43 {
45 fmt::format("{} task failed with unknown exception", task.get_name()));
46 if (abort_on_throw)
47 {
48 std::abort();
49 }
50 }
51 }
52
53 inline void task_worker_loop(
54 JobBoard& job_board,
55 std::atomic<bool>& stop_signal,
56 bool abort_on_throw = true)
57 {
58 static constexpr auto wait_time = std::chrono::milliseconds(100);
59
60 while (!stop_signal.load())
61 {
62 auto task = job_board.wait_for_task(wait_time);
63 if (task != nullptr)
64 {
65 try_do_task(*task, abort_on_throw);
66 }
67 }
68 }
69}
Definition job_board.h:15
Task wait_for_task(const std::chrono::milliseconds &timeout)
Definition job_board.cpp:239
Definition basic_task.h:8
void dump_stacktrace(const std::string &msg)
Definition worker.cpp:102
void task_worker_loop(JobBoard &job_board, std::atomic< bool > &stop_signal, bool abort_on_throw=true)
Definition worker.h:53
void try_do_task(BaseTask &task, bool abort_on_throw=true)
Definition worker.h:22
Definition task.h:15
void do_task()
Definition task_system.cpp:23
virtual const std::string & get_name() const =0
bool is_cancelled()
Definition task_system.cpp:47