Program Listing for File callback_signal.hpp
↰ Return to documentation for file (include/yasmin/callback_signal.hpp)
// Copyright (C) 2026 Maik Knof
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef YASMIN__CALLBACK_SIGNAL_HPP_
#define YASMIN__CALLBACK_SIGNAL_HPP_
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "yasmin/logs.hpp"
#include "yasmin/state.hpp"
#include "yasmin/types.hpp"
namespace yasmin {
class CallbackSignalFuture {
public:
YASMIN_PTR_ALIASES(CallbackSignalFuture)
void wait() const;
bool is_completed() const;
bool has_exception() const;
std::string get_exception_message() const;
private:
struct SharedState {
mutable std::mutex mutex;
std::condition_variable condition;
bool completed{false};
std::exception_ptr exception{};
};
explicit CallbackSignalFuture(std::shared_ptr<SharedState> state);
void set_completed(std::exception_ptr exception = nullptr);
std::shared_ptr<SharedState> state_;
friend class CallbackSignal;
};
class CallbackSignal {
public:
YASMIN_PTR_ALIASES(CallbackSignal)
using CallbackId = std::uint64_t;
using Callback = std::function<void()>;
CallbackId add_callback(Callback callback);
CallbackId add_cancel_callback(const State::SharedPtr &state);
bool remove_callback(CallbackId callback_id);
void clear_callbacks();
std::size_t callback_count() const;
bool empty() const;
void trigger() const;
CallbackSignalFuture::SharedPtr trigger_async() const;
private:
struct CallbackEntry {
CallbackId id;
Callback callback;
};
static void execute_snapshot(const std::vector<CallbackEntry> &callbacks);
std::vector<CallbackEntry> snapshot_callbacks() const;
mutable std::mutex mutex_;
std::vector<CallbackEntry> callbacks_;
std::atomic<CallbackId> next_callback_id_{1};
};
} // namespace yasmin
#endif // YASMIN__CALLBACK_SIGNAL_HPP_