qb  2.0.0.0
C++17 Actor Framework
qb Issue Watch Star Fork Follow @isndev
Loading...
Searching...
No Matches
Main.h
Go to the documentation of this file.
1
29
30#ifndef QB_MAIN_H
31#define QB_MAIN_H
32#include <condition_variable>
34#include <thread>
35#include <vector>
36// include from qb
38#include "CoreSet.h"
39#include "Event.h"
40
41namespace qb {
42
43class Main;
44class VirtualCore;
45class IActorFactory;
46
57constexpr const CoreId NoAffinity = std::numeric_limits<CoreId>::max();
58
68class CoreInitializer : nocopy {
69 friend class Main;
70 friend class VirtualCore;
71
72public:
81 class ActorBuilder {
82 public:
83 using ActorIdList = std::vector<ActorId>;
84
85 private:
86 friend class CoreInitializer;
87
88 CoreInitializer &_initializer;
89 ActorIdList _ret_ids;
90 bool _valid;
91
96 explicit ActorBuilder(CoreInitializer &initializer) noexcept;
97
98 public:
99 ActorBuilder() = delete;
100 ActorBuilder(ActorBuilder const &rhs) = default;
101
122 template <typename _Actor, typename... _Args>
123 ActorBuilder &addActor(_Args &&...args) noexcept;
124
132 [[nodiscard]] bool valid() const noexcept;
139 explicit operator bool() const noexcept;
140
147 [[nodiscard]] ActorIdList idList() const noexcept;
148 };
149
150private:
151 const CoreId _index;
152 ServiceId _next_id;
153 CoreIdSet _affinity;
154 uint64_t _latency;
155
156 qb::unordered_set<ServiceId> _registered_services;
157 std::vector<IActorFactory *> _actor_factories;
158 // CoreSet _restricted_communication; future use
159
160public:
161 CoreInitializer() = delete;
166 explicit CoreInitializer(CoreId index);
168 ~CoreInitializer() noexcept;
169
175 void clear() noexcept;
176
194 template <typename _Actor, typename... _Args>
195 ActorId addActor(_Args &&...args) noexcept;
196
209 [[nodiscard]] ActorBuilder builder() noexcept;
210
219 CoreInitializer &setAffinity(CoreIdSet const &cores = {}) noexcept;
220
233 CoreInitializer &setLatency(uint64_t latency = 0) noexcept;
234
239 [[nodiscard]] CoreId getIndex() const noexcept;
244 [[nodiscard]] CoreIdSet const &getAffinity() const noexcept;
249 [[nodiscard]] uint64_t getLatency() const noexcept;
250};
251
262
272class SharedCoreCommunication : nocopy {
273 friend class VirtualCore;
274 friend class Main;
275 constexpr static const uint64_t MaxRingEvents =
276 (((std::numeric_limits<uint16_t>::max)()) / QB_LOCKFREE_EVENT_BUCKET_BYTES);
278 class Mailbox : public lockfree::mpsc::ringbuffer<EventBucket, MaxRingEvents, 0> {
279 const uint64_t _latency;
280 std::mutex _mtx;
281 std::condition_variable _cv;
282
283 public:
284 explicit Mailbox(std::size_t const nb_producer, uint64_t const latency)
286 , _latency(latency) {}
287
298 void
299 wait() noexcept {
300 if (_latency) {
301 std::unique_lock lk(_mtx);
302 _cv.wait_for(lk, std::chrono::nanoseconds(_latency));
303 }
304 }
305
315 void
316 notify() noexcept {
317 if (_latency)
318 _cv.notify_all();
319 }
320
326 [[nodiscard]] uint64_t
327 getLatency() const noexcept {
328 return _latency;
329 }
330 };
331
332 const CoreSet _core_set;
333 std::vector<std::atomic<bool>> _event_safe_deadlock;
334 std::vector<Mailbox *> _mail_boxes;
335
336public:
337 SharedCoreCommunication() = delete;
339 CoreInitializerMap const &core_initializers) noexcept;
340
341 ~SharedCoreCommunication() noexcept;
342
353 [[nodiscard]] bool send(Event const &event) const noexcept;
354
363 [[nodiscard]] Mailbox &getMailBox(CoreId id) const noexcept;
364
371 [[nodiscard]] CoreId getNbCore() const noexcept;
372};
373
397
408class Main {
409 friend class VirtualCore;
410 constexpr static const uint64_t MaxRingEvents =
411 (((std::numeric_limits<uint16_t>::max)()) / QB_LOCKFREE_EVENT_BUCKET_BYTES);
414
415 static std::vector<Main *> _instances;
416 static std::mutex _instances_lock;
417
418 std::atomic<uint64_t> _sync_start;
419 static void onSignal(int signal) noexcept;
420 static void start_thread(CoreSpawnerParameter const &params) noexcept;
421 static bool __wait__all__cores__ready(std::size_t nb_core,
422 std::atomic<uint64_t> &sync_start) noexcept;
423
424private:
425 std::vector<std::thread> _cores;
426 // Core Factory
427 CoreInitializerMap _core_initializers;
428 std::unique_ptr<SharedCoreCommunication> _shared_com;
429 bool _is_running;
430
431public:
432 using ActorIdList = CoreInitializer::ActorBuilder::ActorIdList;
433
435 Main() noexcept;
437 ~Main() noexcept;
438
448 void start(bool async = true) noexcept;
449
456 [[nodiscard]] bool hasError() const noexcept;
457
465 static void stop() noexcept;
466
473 void join();
474
475public:
493 template <typename _Actor, typename... _Args>
494 ActorId addActor(CoreId index, _Args &&...args);
495
512 [[nodiscard]] CoreInitializer &core(CoreId index);
513
522 void setLatency(uint64_t latency = 0);
523
531 [[nodiscard]] qb::CoreIdSet usedCoreSet() const;
532
542 static void registerSignal(int signum) noexcept;
550 static void unregisterSignal(int signum) noexcept;
557 static void ignoreSignal(int signum) noexcept;
558};
559
570using engine = Main;
571
572} // namespace qb
573#endif // QB_MAIN_H
Unique identifier for actors.
Definition ActorId.h:374
Helper to fluently build multiple Actors for a CoreInitializer.
Definition Main.h:81
ActorBuilder & addActor(_Args &&...args) noexcept
Create and add a new _Actor to the VirtualCore associated with this builder.
ActorIdList idList() const noexcept
Get the list of ActorIds created by this ActorBuilder instance.
bool valid() const noexcept
Checks if all actor additions via this builder were successful up to this point.
Handles pre-start configuration for a single VirtualCore.
Definition Main.h:68
CoreInitializer & setAffinity(CoreIdSet const &cores={}) noexcept
Set the CPU affinity for the VirtualCore associated with this initializer.
void clear() noexcept
Clears all registered actor factories for this initializer.
CoreId getIndex() const noexcept
Gets the CoreId associated with this initializer.
uint64_t getLatency() const noexcept
Gets the currently configured maximum event loop latency (in ns) for this core.
CoreInitializer & setLatency(uint64_t latency=0) noexcept
Set the maximum event loop latency for the VirtualCore.
ActorId addActor(_Args &&...args) noexcept
Create and add a new _Actor to this VirtualCore.
CoreIdSet const & getAffinity() const noexcept
Gets the currently configured CPU affinity set for this core.
ActorBuilder builder() noexcept
Get an ActorBuilder for this CoreInitializer.
Manages a set of core identifiers.
Definition CoreSet.h:47
Base class for all events in the actor system.
Definition Event.h:85
Interface for actor factory classes.
Definition Actor.h:878
The main controller for the QB Actor Framework engine.
Definition Main.h:408
Main() noexcept
Default constructor.
Manages inter-core communication infrastructure (mailboxes).
Definition Main.h:272
Manages a virtual processing core (worker thread) in the actor system.
Definition VirtualCore.h:75
Multi-Producer Single-Consumer ring buffer with fixed number of producers.
Definition mpsc.h:58
Core set management for the QB Actor Framework.
Event system for the QB Actor Framework.
std::unordered_map< K, V, H, E, A > unordered_map
The primary unordered map implementation.
Definition unordered_map.h:90
std::unordered_set< K, H, E, A > unordered_set
The primary unordered set implementation.
Definition unordered_set.h:81
uint16_t CoreId
Type definition for core identifiers.
Definition ActorId.h:51
uint16_t ServiceId
Type definition for service identifiers.
Definition ActorId.h:59
CoreIdBitSet CoreIdSet
Efficient set implementation for storing CoreId values.
Definition ActorId.h:363
void start(bool async=true) noexcept
Start the engine and its VirtualCore worker threads.
void join()
Wait for the engine and all its VirtualCore threads to terminate.
void notify() noexcept
Notifies a waiting thread (VirtualCore) that an event might be available in this mailbox.
Definition Main.h:316
static void stop() noexcept
Stop the engine and all its VirtualCores gracefully.
constexpr const CoreId NoAffinity
Special constant indicating that no CPU affinity is desired.
Definition Main.h:57
bool send(Event const &event) const noexcept
Send an event to the mailbox of its destination VirtualCore.
static void unregisterSignal(int signum) noexcept
Unregister a previously registered system signal from engine handling.
Main engine
Alias for the Main class.
Definition Main.h:570
Mailbox & getMailBox(CoreId id) const noexcept
Get the mailbox for a specific VirtualCore.
ActorId addActor(CoreId index, _Args &&...args)
Add a new actor to a specified VirtualCore before the engine starts.
CoreInitializer & core(CoreId index)
Get the CoreInitializer for a specific VirtualCore index.
static void ignoreSignal(int signum) noexcept
Ignore a system signal, preventing the engine or default OS handler from processing it.
qb::CoreIdSet usedCoreSet() const
Get the set of CoreIds that are currently configured to be used by the engine.
static void registerSignal(int signum) noexcept
Register a system signal to be handled by the engine (results in graceful shutdown).
uint64_t getLatency() const noexcept
Get the latency setting for this mailbox.
Definition Main.h:327
CoreId getNbCore() const noexcept
Get the number of VirtualCores configured in the system.
void setLatency(uint64_t latency=0)
Set the default event loop latency for all VirtualCores.
bool hasError() const noexcept
Check if any VirtualCore encountered an error and terminated prematurely.
qb::unordered_map< CoreId, CoreInitializer > CoreInitializerMap
Map of CoreId to CoreInitializer objects.
Definition Main.h:261
void wait() noexcept
Waits for a notification on this mailbox, up to its configured latency.
Definition Main.h:299
Event event
Alias for the base Event class.
Definition Event.h:385
Multiple-Producer Single-Consumer lockfree queue.
Internal structure for passing parameters to core spawning functions.
Definition Main.h:384
const CoreId id
The CoreId of the VirtualCore being spawned.
Definition Main.h:386
SharedCoreCommunication & shared_com
Reference to the shared communication infrastructure.
Definition Main.h:392
std::atomic< uint64_t > & sync_start
Atomic counter for synchronizing core startup.
Definition Main.h:395
CoreInitializer & initializer
Reference to the CoreInitializer for this core.
Definition Main.h:389
nocopy()=default
Default constructor.
Optimized unordered map implementations.