Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/host_sanitizers.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ name: Host sanitizers (TSan / ASan)
# scheduler, deferred dispatchers), and most defects found in review have been
# data races, deadlocks, and use-after-frees - exactly the classes these
# sanitizers detect mechanically. Runs whenever RTPS or its concurrency
# building blocks change.
# building blocks change. The EventManager test (pc/tests/event_manager.cpp)
# runs here too, for the same reasons.

# Minimal token scope: build + run tests, never writes.
permissions:
Expand All @@ -21,10 +22,12 @@ on:
- "components/task/**"
- "components/timer/**"
- "components/cdr/**"
- "components/event_manager/**"
- "lib/espp.cmake"
- "pc/tests/rtps_*"
- "pc/tests/socket_reactor.cpp"
- "pc/tests/thread_pool.cpp"
- "pc/tests/event_manager.cpp"
- ".github/workflows/host_sanitizers.yml"
workflow_dispatch:

Expand Down Expand Up @@ -97,7 +100,7 @@ jobs:
# docker matrix covers them); everything else runs standalone. The
# generous per-test timeout absorbs the sanitizer's slowdown; a hang
# (e.g. a deadlock TSan cannot see) still fails the job.
for t in pc/build/rtps_* pc/build/socket_reactor pc/build/thread_pool; do
for t in pc/build/rtps_* pc/build/socket_reactor pc/build/thread_pool pc/build/event_manager; do
[ -x "$t" ] || continue
name=$(basename "$t")
case "$name" in *interop*) continue;; esac
Expand Down
24 changes: 24 additions & 0 deletions components/event_manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,30 @@ EventManager. As noted in a few places, it is recommended to use a
(de-)serialization library such as espp::serialization / alpaca for transforming
data structures to/from `std::vector<uint8_t>` for publishing/subscribing.

## Threads and callbacks

Each topic's callbacks run one after another on that topic's thread, in the
order the subscribers were added, and data published on a topic is delivered
in the order it was published. One slow callback delays every other subscriber
of the same topic (but not other topics).

Every function is thread safe and can be called from any thread, including from
inside a subscriber callback: a callback can publish, subscribe, or remove its
own subscription. When `remove_subscriber()` returns, that callback is not
running and will not be called again, so an object can call it from its
destructor and then be destroyed safely. To guarantee that,
`remove_subscriber()` (and `clear()`) wait for the callback they remove if it is
running on another thread, so don't call them while holding a lock that the
callback takes. They can't wait in two cases, which would deadlock: when called
from that callback itself, and when that callback is waiting in turn for the
caller (callbacks of two topics removing each other's subscribers).

The wait runs at the topic task's priority, which is 0 unless the
`task_config` passed to `add_subscriber()` sets one, so a high priority task
removing a subscriber can be held up by a low priority topic. `add_subscriber()`
returns false while `clear()` runs. Data still queued for a topic when its last
subscriber leaves is dropped.

## Example

The [example](./example) shows some basic usage for the `EventManager` which
Expand Down
12 changes: 7 additions & 5 deletions components/event_manager/example/main/event_manager_example.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <atomic>
#include <chrono>
#include <thread>
#include <vector>
Expand Down Expand Up @@ -31,8 +32,9 @@ extern "C" void app_main(void) {
const std::string event1 = "battery/state";
const std::string event2 = "drive/control";

static int num_published = 0;
static int num_received = 0;
// updated from both tasks and both topics' subscriber threads
static std::atomic<int> num_published = 0;
static std::atomic<int> num_received = 0;

// Make a task which has a pub/sub in it. NOTE: in real code, this would
// likely be within a custom class and the registration would happen in the
Expand Down Expand Up @@ -184,10 +186,10 @@ extern "C" void app_main(void) {
em.remove_subscriber(event1, "task 2");
//! [event manager example]

logger.info("Published {} times", num_published);
logger.info("Received {} times", num_received);
logger.info("Published {} times", num_published.load());
logger.info("Received {} times", num_received.load());

if (num_published != num_received) {
if (num_published.load() != num_received.load()) {
logger.error("Mismatch between published and received!");
} else {
logger.info("Published and received match!");
Expand Down
167 changes: 133 additions & 34 deletions components/event_manager/include/event_manager.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
#pragma once

#include <condition_variable>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
Expand All @@ -22,13 +26,31 @@ namespace espp {
* @note In c++ objects, it's recommended to call the
* add_publisher/add_subscriber functions in the class constructor and
* then to call the remove_publisher/remove_subscriber functions in the
* class destructor.
* class destructor. When remove_subscriber() returns, the callback is
* not running and will not be called again, so the object can be
* destroyed safely right after it (see remove_subscriber() for the two
* cases where it can't wait).
*
* @note Every function is thread safe and can be called from any thread,
* including from inside a subscriber callback (for example a callback
* that removes its own subscription). remove_subscriber() and clear()
* wait for a callback they remove that is running on another thread to
* return, so don't call them while holding a lock which that callback
* takes. They wait at the topic task's priority: a high priority caller
* can be held up by a topic whose task has a low priority
* (Task::BaseConfig::priority, 0 by default), so give the topic's
* task_config a priority that suits the code removing its subscribers.
*
* @note Data published on a topic is queued and delivered in order on the
* topic's thread. Data still queued when the topic's last subscriber is
* removed is dropped. When C++ exceptions are enabled, an exception
* thrown by a callback is logged and the other callbacks still run.
*
* @note It is recommended (unless you are only interested in events and not
* data or are only needing to transmit actual strings) to use a
* serialization library (such as espp::serialization - which wraps
* alpaca) to serialize your data structures to string when publishing
* and then deserialize your data from string in the subscriber
* alpaca) to serialize your data structures to bytes when publishing
* and then deserialize your data from bytes in the subscriber
* callbacks.
*
* \section event_manager_ex1 Event Manager Example
Expand Down Expand Up @@ -57,6 +79,12 @@ class EventManager : public espp::BaseComponent {
EventManager(EventManager &&) = delete;
EventManager &operator=(EventManager &&) = delete;

/**
* @brief Destroy the EventManager, stopping every topic's thread (see
* clear()).
*/
~EventManager();

/**
* @brief Register a publisher for \p component on \p topic.
* @param topic Topic name for the data being published.
Expand All @@ -69,15 +97,17 @@ class EventManager : public espp::BaseComponent {
/**
* @brief Register a subscriber for \p component on \p topic.
* @param topic Topic name for the data being subscribed to.
* @param component Name of the component publishing data.
* @param callback The event_callback_fn to be called when receicing data on
* @param component Name of the component subscribing to the data.
* @param callback The event_callback_fn to be called when receiving data on
* \p topic.
* @param stack_size_bytes The stack size in bytes to use for the subscriber
* @note The stack size is only used if a subscriber is not already registered
* for that topic. If a subscriber is already registered for that topic,
* the stack size is ignored.
* @note The stack size is only used when the topic's thread is created. If
* a subscriber is already registered for that topic (or the topic's
* thread is still finishing a delivery after its last subscriber was
* removed, and is reused), the stack size is ignored.
* @return True if the subscriber was added, false if it was already
* registered for that component.
* registered for that component, the callback is empty, clear() is
* running, or the topic's thread could not be started.
*/
bool add_subscriber(const std::string &topic, const std::string &component,
const espp::EventManager::event_callback_fn &callback,
Expand All @@ -86,15 +116,17 @@ class EventManager : public espp::BaseComponent {
/**
* @brief Register a subscriber for \p component on \p topic.
* @param topic Topic name for the data being subscribed to.
* @param component Name of the component publishing data.
* @param callback The event_callback_fn to be called when receicing data on
* @param component Name of the component subscribing to the data.
* @param callback The event_callback_fn to be called when receiving data on
* \p topic.
* @param task_config The task configuration to use for the subscriber.
* @note The task_config is only used if a subscriber is not already
* registered for that topic. If a subscriber is already registered for
* that topic, the task_config is ignored.
* @note The task_config is only used when the topic's thread is created. If
* a subscriber is already registered for that topic (or the topic's
* thread is still finishing a delivery after its last subscriber was
* removed, and is reused), the task_config is ignored.
* @return True if the subscriber was added, false if it was already
* registered for that component.
* registered for that component, the callback is empty, clear() is
* running, or the topic's thread could not be started.
*/
bool add_subscriber(const std::string &topic, const std::string &component,
const espp::EventManager::event_callback_fn &callback,
Expand All @@ -121,38 +153,105 @@ class EventManager : public espp::BaseComponent {

/**
* @brief Remove \p component's subscriber for \p topic.
* @details When it returns, the callback is not running and will not be
* called again, and it has been destroyed unless it was still
* running (it is then destroyed on the topic's thread once it
* returns). It can't wait for the callback in two cases, which
* would deadlock: when called from that callback itself, and when
* the callback is waiting in turn for the calling thread (callbacks
* of two topics removing each other's subscribers). Removing the
* topic's last subscriber stops the topic's thread and drops any
* data still queued for it.
* @param topic The topic that \p component was subscribing to.
* @param component The component for which the subscriber was registered.
* @return True if the subscriber was removed, false if it was not
* registered.
* registered. It waits for the callback in both cases: one that
* removed itself (or that clear() removed) can still be running.
*/
bool remove_subscriber(const std::string &topic, const std::string &component);

/**
* @brief Remove every publisher and subscriber and stop every topic's
* thread.
* @details Waits for callbacks running on other threads to return (except
* in the two cases described in remove_subscriber()).
* add_subscriber() returns false while it runs. The EventManager
* can be used again afterwards.
*/
void clear();

protected:
EventManager()
: espp::BaseComponent("Event Manager") {}

struct SubscriberData {
std::mutex m;
bool notified = false; // Allows cv to ignore spurious wakeups
std::condition_variable cv;
std::deque<std::vector<uint8_t>> deq;
/// One component's subscription. Shared by the topic's subscriber list and
/// by the snapshot a delivery in progress iterates, so a callback is never
/// destroyed while it runs.
struct Subscriber {
Subscriber(const std::string &component, const event_callback_fn &callback)
: component(component)
, callback(callback) {}
const std::string component;
/// Called by the topic's thread only while Topic::calling points at this
/// subscriber. Once it is removed and not running, its remover takes it
/// out, so that it is destroyed by remove_subscriber().
event_callback_fn callback;
bool removed{false}; ///< Guarded by Topic::m. Set when removed; never called from then on.
};
using SubscriberList = std::vector<std::shared_ptr<Subscriber>>;

bool subscriber_task_fn(const std::string &topic, std::mutex &m, std::condition_variable &cv,
bool &task_notified);

std::recursive_mutex events_mutex_;
detail::EventMap events_;

std::recursive_mutex callbacks_mutex_;
std::unordered_map<std::string, std::vector<std::pair<std::string, event_callback_fn>>>
subscriber_callbacks_;
/// The state of one topic that has subscribers. Owned through a shared_ptr
/// so publish() and the removal of the last subscriber can overlap safely.
struct Topic {
explicit Topic(const std::string &name)
: name(name) {}
/// Stops the topic's thread and joins it.
~Topic();
const std::string name;
std::mutex m; ///< Guards the members below, up to subscribers.
std::condition_variable cv; ///< Wakes the topic's thread (data queued or stopping).
/// Signalled when a callback or a delivery finishes, or the topic is reused.
std::condition_variable idle_cv;
std::deque<std::vector<uint8_t>> queue;
/// Set when the topic loses its last subscriber. Cleared again if a new
/// subscriber reuses the topic before its thread has exited.
bool stopping{false};
bool exited{false}; ///< Set by the topic's thread when it sees stopping and exits.
/// True while the topic's thread delivers an event: from taking the
/// subscriber snapshot until it has let go of it again.
bool busy{false};
const Subscriber *calling{nullptr}; ///< The subscriber whose callback is running.
/// Replaced, never changed in place, with both EventManager::mutex_ and m
/// held, so holding either one is enough to read it.
std::shared_ptr<const SubscriberList> subscribers;
/// What the topic's thread is waiting for while it is blocked in
/// remove_subscriber() or clear(): a callback of *waiting_for on
/// waiting_on, or (waiting_for null) the end of waiting_on's last
/// delivery. Guarded by the wait-graph mutex; used to skip a wait that
/// would deadlock.
Topic *waiting_on{nullptr};
const std::string *waiting_for{nullptr};
std::unique_ptr<Task> task;
};

std::recursive_mutex tasks_mutex_;
std::unordered_map<std::string, std::unique_ptr<Task>> subscriber_tasks_;
static bool deliver_next(Topic &topic);
static Topic *delivering_topic();
static bool is_delivering(const Topic &topic);
static bool is_running(const Topic &topic, const std::string *component);
static bool waits_for(const Topic &from, const Topic &self);
static bool wait_while_running(Topic &topic, const std::string *component);
static void retire(Topic &topic);
static bool revive(Topic &topic, const std::shared_ptr<Subscriber> &subscriber,
std::shared_ptr<const SubscriberList> &replaced);
void take_finished_topics(std::vector<std::shared_ptr<Topic>> &finished);

std::recursive_mutex data_mutex_;
std::unordered_map<std::string, SubscriberData> subscriber_data_;
std::mutex mutex_; ///< Guards the members below.
std::unordered_map<std::string, std::vector<std::string>> publishers_;
std::unordered_map<std::string, std::shared_ptr<Topic>> topics_;
/// Topics that lost their last subscriber and whose thread hasn't been
/// joined yet. One is joined once its thread is no longer delivering, by
/// whichever call notices first.
std::vector<std::shared_ptr<Topic>> retiring_;
int clearing_{0}; ///< Number of clear() calls running (plus one once the destructor runs).
};
} // namespace espp
8 changes: 5 additions & 3 deletions components/event_manager/include/event_map.hpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#pragma once

#include <functional>
#include <algorithm>
#include <cstdint>
#include <iterator>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>

namespace espp {
Expand Down Expand Up @@ -31,7 +33,7 @@ std::pair<bool, uint32_t> get_index_in_container(const T &value, const C &contai
if (exists) {
index = std::distance(container.begin(), iter);
}
return {exists, index};
return {exists, static_cast<uint32_t>(index)};
}
} // namespace detail
} // namespace espp
Loading
Loading