Loading...
Searching...
No Matches
CancelToken.h
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#pragma once
13
14#include <atomic>
15#include <memory>
16#include <stdexcept>
17#include <string>
18
19namespace eonc {
20
22class JobCancelled : public std::runtime_error {
23public:
24 explicit JobCancelled(const char *site = "cancelled")
25 : std::runtime_error(std::string("job cancelled at ") +
26 (site != nullptr ? site : "cancelled")) {}
27};
28
31public:
32 CancelToken() : flag_(std::make_shared<std::atomic<bool>>(false)) {}
33
34 void request() noexcept {
35 if (flag_) {
36 flag_->store(true, std::memory_order_release);
37 }
38 }
39
40 void reset() noexcept {
41 if (flag_) {
42 flag_->store(false, std::memory_order_release);
43 }
44 }
45
46 [[nodiscard]] bool requested() const noexcept {
47 return flag_ && flag_->load(std::memory_order_acquire);
48 }
49
50 void poll(const char *site = "step") const {
51 if (requested()) {
52 throw JobCancelled(site);
53 }
54 }
55
56private:
57 std::shared_ptr<std::atomic<bool>> flag_;
58};
59
60} // namespace eonc
void poll(const char *site="step") const
Definition CancelToken.h:50
void request() noexcept
Definition CancelToken.h:34
bool requested() const noexcept
Definition CancelToken.h:46
std::shared_ptr< std::atomic< bool > > flag_
Definition CancelToken.h:57
void reset() noexcept
Definition CancelToken.h:40
Cooperative stop. Loops poll and throw; they do not abort the process.
Definition CancelToken.h:22
JobCancelled(const char *site="cancelled")
Definition CancelToken.h:24
RAII resource manager for the ARTn C library with global synchronization.