Principle:AGenUI AGenUI Engine Singleton Lifecycle
| Knowledge Sources | |
|---|---|
| Domains | Software_Architecture, Concurrency |
| Last Updated | 2026-10-24 17:21 GMT |
Overview
A thread-safe singleton lifecycle pattern that guarantees exactly one engine instance is created, shared across all callers, and destroyed cleanly with its dependent resources in reverse initialization order.
Description
The Singleton pattern restricts instantiation to exactly one object, ensuring a single shared point of access for global state and services. In a multi-threaded environment, naive singleton initialization suffers from race conditions: two threads may simultaneously see the instance as null and both create a new object. The call-once idiom (using `std::call_once` with `std::once_flag`) solves this at the language level by guaranteeing the initialization lambda executes exactly once across all threads, even under concurrent entry.
This principle also encompasses ordered lifecycle management. The singleton's `start()` method creates dependent subsystems (managers, registries, a shared worker thread) in a specific order. Its `stop()` method destroys them in reverse order — the worker thread is torn down first so no task ever runs against a freed object, then surface managers are detached, then singleton modules are deleted. This prevents use-after-free and dangling-pointer bugs during shutdown.
Usage
Use this principle when a system needs exactly one shared engine instance that:
- Owns long-lived global resources (thread pools, managers, registries)
- Must be initialized exactly once, safely, from any thread
- Must shut down cleanly with all dependent resources freed in correct order
Theoretical Basis
The core invariant is established by `std::call_once`:
// Thread-safe singleton initialization
static std::once_flag g_initFlag;
static std::atomic<AGenUIEngine*> g_engine(nullptr);
IAGenUIEngine* initAGenUIEngine() {
std::call_once(g_initFlag, []() {
auto* engine = new AGenUIEngine();
engine->start(); // create subsystems
g_engine.store(engine);
});
return g_engine.load();
}
The lifecycle invariant (reverse-order destruction):
start(): subsystems created in order A → B → C → D
stop(): subsystems destroyed in order D → C → B → A
The shared worker thread is destroyed first in `stop()`, guaranteeing no queued task runs after any object it references has been freed.
Practical Guide
- Call `initAGenUIEngine()` once at application launch; subsequent calls return the same pointer.
- Store the returned `IAGenUIEngine*` for the application lifetime.
- Call `destroyAGenUIEngine()` only at application shutdown, after all surfaces are destroyed.
- Never call `initAGenUIEngine()` and `destroyAGenUIEngine()` concurrently.