O que faz
- <code>CSignal</code>, um sinal com agregação de valores de retorno e conexões com escopo
- Sinal concorrente como tipo separado
- Barramento com publicação imediata, adiada e persistente (sticky)
- Uma exceção em um slot é tratada sem abortar a emissão
Medido
- Release, Linux GCC / Windows MSVC. Emitir para 0 conexões: 0,54 ns. Para 1: 2,76 e 2,91 ns. Para 100: 153 e 170 ns (meta de 200 ns)
- Zero alocações em 10.000 emissões
What this module did with what already existed, and why
The module existed and was correct. It had all the reentrancy semantics in place and passed 164 checks in smoke. It was rewritten from scratch for a concrete reason: the spec opens by forbidding, by name, exactly what it used.
*"An event bus is where naive implementations quietly destroy performance: **
std::functionallocations,shared_ptrrefcount traffic**,std::map<type_index, ...>lookups, and a heap allocation per emission. None of that is acceptable here."*
Before touching a single line, I measured what was there against the spec targets:
| target | spec | the old design |
|---|---|---|
| emit to 0 connected | < 2 ns | 3.79 ns |
| emit to 1 | < 5 ns | 25.3 ns |
| emit to 100 | < 200 ns | 1,589 ns |
| allocations on emit | zero | zero ✓ |
| connect 4 | no heap | 7 allocations |
Eight times over in the hundred case. That cannot be fixed by fine-tuning. One std::function per slot, inside a shared_ptr, and one copy of the shared_ptr per call during emission: that is three indirections and a pair of atomic operations per slot, and none of them goes away without changing the design.
Writing "the old design was slow" without a number is an opinion. That is why the table comes first.
---
The design, and what each choice buys
A slot is a pair: a context pointer and a function pointer. Sixteen bytes, four per cache line. Emission is a linear walk over a contiguous vector of these pairs, with no list, no node, no virtual call and no reference counting.
The cold data lives in another vector. The generation and the priority are needed when connecting and disconnecting, and never when emitting. Mixing the two in the same record would put 24 bytes per slot on the cache line of the hot walk: two and a half per line instead of four.
Emitting to nobody is one read and one branch. The count is in the header, visible to the compiler, and there is no call to cross. The spec asks for "a single predictable branch", and that is literally what it is. BeginEmit and EndEmit are inline too. With them out of line, emitting to one connected slot fluctuated between 4.5 and 5.5 ns, right on the target of five.
The std::function that does not exist
*"No
std::function. Callbacks are stored as raw context plus erased function pointer. A capturing lambda connects by binding to a caller-owned object, and the API makes the lifetime requirement explicit in the name."*
That is why ConnectBorrowed has that name, and not Connect: it does not copy what it receives, it stores the address. The rvalue reference overload is deleted, so passing a temporary to it is a compile error instead of turning into a run-time defect.
---
The targets, measured
| target | Linux Release | Windows Release |
|---|---|---|
| emit to 0 | 0.00 ns | 0.54 ns |
| emit to 1 | 2.76 ns | 2.91 ns |
| emit to 100 | 153 ns (1.53/slot) | 170 ns (1.70/slot) |
| allocations on emit | zero in 10,000 | zero |
| connect 4 | no heap | no heap |
| disconnect at 1 / 100 / 10,000 | O(1) measured | O(1) measured |
Three things about these numbers that cannot be left out
1. What is measured is the minimum of five repetitions, never a single pass. This machine is noisy: the same "emit to a hundred" measurement gave between 165 and 270 ns over twelve runs of the same binary, and the gate failed once in four. A test that fails once in four is worse than none, because it teaches people to ignore red. The minimum is the right estimator for latency: of the repetitions, it is the one the system interrupted least.
2. The hundred target is also compared against the floor. 200 ns for a hundred slots is 2 ns per slot, which is roughly what an indirect call costs on this machine. The test walks an identical vector of pairs by hand and compares. That is what catches a new indirection creeping in, something the absolute number would not catch. Measured: the signal comes in below the hand-written walk, because the latter goes through a std::vector with range-for and the former is a raw pointer loop.
3. Time targets are not required in Debug or under a sanitizer. /Od /RTC1 on Windows gives 4.57 / 14.84 / 409 ns. Under TSan the same operation is multiplied by twenty. The number is printed in every configuration. Only the gate changes.
---
The bus
The address of a type serves as identity, but it does not serve as an index. The previous version used the address of one static variable per type: that is 64 bits scattered across the address space, and getting to the signal requires a map, which is exactly what the spec forbids in dispatch. A counter assigned during static initialization gives 0, 1, 2, … and dispatch becomes a vector index.
Publish delivers immediately, on the caller's stack. Post copies the bytes into a ring and delivery only happens in Drain. That is why it only accepts trivially copyable types, with rejection at compile time, without relying on a warning.
Sticky events keep the last value per type and deliver that value to whoever subscribes later, from inside the Subscribe call itself. They are for state ("the server is up", "the window is this size"), and not for occurrences.
---
The C layer, and the defect it had
"the C side is a type-id-plus-blob API"
In C there is no TypeIdOf<T>(), because there is no T. The type number comes from the caller, and it is what decides dispatch.
The first version ignored that number. I wrote ETL_UNUSED( uType ) in three places and moved on: all C subscribers landed in the same place, and a Publish of one number delivered to whoever had subscribed to another. The C test has a case that subscribes to two different numbers and requires that one not receive the other's. Without that case, the defect gets through.
The fix was to expose on CEventBus the raw entry point, which already existed internally and takes the number from outside. The first attempt at that fix was also wrong: I offset the raw numbers by RAW_BASE inside the same dense vector, which made the index exceed one billion and the resize blow up with bad_alloc. Now RAW_BASE is a marker: it says which of the two dense vectors to look in.
What is lost when crossing: in C++ the compiler guarantees that the publisher and the subscriber agree on the type. In C that guarantee does not exist, and a mistake in the number delivers the bytes of one event to a subscriber expecting another. That is the price, and it is stated so that the typed layer remains the preferred one.
---
The concurrent variant
*"The thread-safe variant is a separate type, not a runtime flag.
CSignalhas no synchronization at all. Do not make the single-threaded user pay for an atomic."*
A run-time flag would put a branch (and, worse, a shared read) on the path that the spec says must cost less than two nanoseconds. The only way to guarantee that whoever does not need it does not pay is to not have the code there, and that can be checked: CSignal<int> takes 288 bytes, CConcurrentSignal<int> takes 352.
What it guarantees: connecting, disconnecting and emitting from different threads does not corrupt the list. Measured with four threads going back and forth and one million deliveries. What it does not guarantee: that the handler is safe, or ordering across threads.
Connecting, disconnecting and emitting the same signal from inside a slot works as in CSignal: the nested emission walks the slots that were live when it started, and whatever was connected or disconnected inside it takes effect at the end of the outermost emission. The signal records which thread is emitting, and a Connect, Disconnect or Emit made by that thread does not take again the lock it already holds. Until 2026-10-05 connecting from inside deadlocked the thread, and until 2026-10-06 emitting from inside did too. The tests run the emissions on a thread with a five-second deadline: a deadlock becomes a failure, and not a hung ctest.
A slot may throw an exception. Emission enters and leaves the core through a scope (SEmitScope), and the depth also goes down when the exception passes through. Until 2026-10-11 the BeginEmit/EndEmit pair was called by hand, and an exception left the depth marked forever: the signal said it was emitting, and every Connect made afterwards was deferred to an end of emission that never came (in CSignal, CSignalR and CConcurrentSignal). In the concurrent one, the live count is also published on the exception exit. The bus does not change: Publish is noexcept, and an exception there terminates the process.
The common path pays one extra relaxed read, next to the lock it takes anyway. Measured in the test (one thread, one slot, no contention, WSL with the machine busy): from 49 to 71 ns before, from 44 to 70 ns after. The variation between runs is larger than the difference. A slot that waits on another thread that connects to or emits on this signal still deadlocks, as with any lock held while calling outside code.
---
The defects the construction found
Compacting at the end of every emission was silent corruption. It looked like cheap housekeeping, but compacting moves the live slots, and the index the caller stored in the SConnection ends up pointing to another one, or outside the list. The symptom is not a crash. It is a Disconnect that returns false for no reason, much later and somewhere else. Now the tombstones stay, and are reused in place.
My "zero allocation" oracle did not see what it claimed to see. The core uses malloc (it must not throw), and malloc goes underneath the operator new that the test replaces. The counter is still valid for emission, which calls neither. For internal capacity, the oracle now checks whether the vector still points inside the object itself.
Replacing the global allocator halfway is a trap, and only ASan showed it. The test replaced operator new, but not the nothrow variant, which the bus uses. The memory came from the system allocator and the test's operator delete released it with free. In a normal run it goes unnoticed. Under ASan it is alloc-dealloc-mismatch and the program aborts.
---
---
The audit against spec 07, and the defect it found
The spec surface was complete: CSignal, CSignalR with the four aggregations, CScopedConnection, CTrackable, CConcurrentSignal, CEventBus with Publish/Post/ PublishSticky/Drain, the IDispatcher seam, and the C layer with twenty-three entry points. That did not change.
What the audit did was look for what nobody called, and it found two things. One of them was a serious defect.
Compact() invalidated connections already handed out, and nothing exercised it
The spec names that function:
*"Disconnected slots leave a tombstone that is reclaimed on the next connect or on an explicit
Compact()."*
It moves the live slots down, covering the tombstones. And an SConnection is { uIndex, uGeneration }: the caller has a copy, and nobody can update it.
The path to the damage is short:
- three connections. The middle one is disconnected and leaves a tombstone.
Compact()runs, and the third one moves down from index 2 to 1.- the owner of the third calls
Disconnectwith the old index. Removerefuses, andCScopedConnectionignores the result.- the slot stays alive, pointing to an object that no longer exists.
The next emission calls that slot.
**Compact() was the only public function of the module that no case touched.** Measured: of the seventeen public pieces the spec names, two did not appear even once in event_signal.cpp: this one and SetDispatcher.
The fix, and what it costs
Remove now searches by generation when the index does not match, and only after a compaction has taken place that actually moved something. The generation comes from a monotonic counter, and so it is unique among the live slots: the search cannot hit the wrong one.
The cost is declared. After a compaction, a Remove that misses the index costs one pass over the vector. The spec forbids scanning to disconnect, but what it forbids is the normal case, and this one only happens to whoever asked for the compaction. Without Compact(), Remove is exactly what it always was: an index and a generation check.
The module already had the precedent written down, for connections born inside an emission:
"So here, and only here, search by generation. It is a scan, and the spec forbids scanning to disconnect, but what it forbids is the normal case."
And the test passed for the wrong reason
The first version of the scope guard case passed with the defect in place. A Connect reuses whatever tombstone there is. The guard connected after the tombstone existed, landed in it, Compact() moved nothing, and the case measured the happy path dressed up as the hard path.
Now the guard connects first, and the tombstone opens below it. With the fix turned off by hand, the four checks of this section fail. With it, they pass.
The dispatcher seam was declared and had never seen an implementation
All that was known about it was that it compiled. Now there is a test dispatcher that counts the notifications and drains whenever it wants, which is the design the seam has to allow, because **OnWorkPosted is called from inside Post** and draining there would reenter the bus in the middle of one of its operations.
What the test requires:
Postenqueues and does not publish. Without a dispatcher, nothing is delivered untilDrain.- the dispatcher is notified **once per
Post**. Without this check, a seam that never calledOnWorkPostedwould pass everything else, because delivery happens the same way. - the notification delivers nothing:
Drainis still what delivers. - passing null turns off the dispatcher, and the bus keeps working. A
Postwhose event got stuck for lack of someone to notify would be a queue growing silently.
---
---
Compaction crosses to C, and brings along the missing number
ETLC_Signal_Compact and ETLC_Signal_DeadCount. Compaction was the last thing in spec 07 that existed only in C++.
DeadCount did not exist on either side, and without it compaction is a guess
Compact() costs one pass over the vector and cannot run during an emission. Whoever calls it now and then "to be safe" pays without knowing whether there was anything to reclaim. Whoever never calls it lets the vector grow with holes. There was no way to answer the question, not even in C++.
It is also what makes compaction observable. Compact() returns void and moves slots out from under the caller. Without a number that changes, a test cannot tell a compaction that ran from one that gave up on entry, which is what it does, silently, when an emission is in progress or when there is no tombstone at all.
On the C side it returns how many it reclaimed, computed by the difference
The value does not come from what was there before. Compact gives up without a word in the two cases above, and returning the previous value would give a number to whoever requested compaction during an emission, precisely when it did not run. The difference gives zero in both, which is the truth.
What the C test requires, and why
The check that matters is this one: a handle handed out before compaction must keep disconnecting the right slot. The test connects A, B and D, kills the middle one (which is what forces the one below to move down), compacts, and only then disconnects D with the handle from before.
If Disconnect gave up on seeing that the index no longer matches, an object destroyed after a compaction would leave its slot alive pointing to dead memory, and the next emission would call that slot. The C++ side solves this by searching by generation, and from here there is nothing to do: the contract crosses whole.
The C test went from 44 to 53 checks.
---
The three time gates, and what sequential measurement was hiding
Running the test suite in Release with --parallel 8 made this test fail on all three. None pointed to a regression in the module, and the hundred-slot one gave a very wrong number.
The hundred-slot gate: the signal was not getting fatter
The gate compares emitting to a hundred connected slots with the same walk by hand over a vector of a hundred pointers. It is the gate that does not depend on this machine's clock, and the one that would catch a new indirection creeping in.
The two were measured in sequence: fifteen repetitions of one, then fifteen of the other. With the machine under contention:
| measured in sequence | measured alternating | |
|---|---|---|
| emit to a hundred | 305.2 ns | 145.9 ns |
| the same walk by hand | 212.3 ns | 142.8 ns |
| ratio | 1.44 (gate: 1.25) | 1.02 |
The signal was not getting fatter. It was the walk that had been measured at a different moment. Alternated, emitting comes out practically equal to the hand-written walk, which is the result the design predicted and which sequential measurement was hiding in both directions.
That is why MeasureMinPair came into this file. It already existed in console_cli.cpp, written after the snprintf gate broke exactly this way. The note there says "Measuring one and then the other does not work for comparing the two", and here one was measured and then the other.
The zero-connected gate: the target was right up against the floor
It requires less than 2 ns for one read and one branch. The empty loop on this machine costs about 1.3. The target is less than half a nanosecond from the floor, and any contention on the processor eats it.
It had no guard at all, unlike the hundred-slot gate in the same file, which already had one. It is now measured alternating with the empty loop, and it is only required when the floor is below 2.
The one-connected gate: the same, and the note on when an empty loop is enough
Five nanoseconds is roughly what an indirect call costs here. It received the same guard.
Here an empty loop is enough as a floor, which is not always true. What is measured is an indirect call, which lives in the registers just as the loop does. In time.civil it was not enough: there, what is measured walks 56 MB of memory, and the floor had to become a memory sweep. The note is written in that README, and the two together state the rule:
The floor has to measure the resource that is scarce. A floor that does not measure what the measurement consumes never fires, and a guard that never fires is worse than none: it gives the impression that the problem is handled.
---
The target that passed because the compiler had deleted the measurement
On the first run of the linux-release preset, the gate emitting to nobody costs less than 2 ns measured this. The output is the capture of that run, from before 2026-10-05, originally printed in Portuguese (shown here translated):
emit to ZERO connected: 0.00 ns (target < 2)Three runs in a row, always the same number. On MSVC it measured 0.54.
Zero is not a small time: it is the absence of a measurement
Emitting to zero connected slots has no observable effect. The signal was a local object the compiler sees in full, the loop touched nothing else, and GCC proved that it did nothing and deleted the whole loop.
The gate passed. And the property the spec promises, "a single predictable branch", was not being exercised on that compiler, in any run.
A target that passes because nothing ran is worse than a target that fails: red raises a question, green does not.
The fix: the signal has to be opaque to the optimizer
CSignal< int > * volatile pSignal = &Signal;
...
pSignal->Emit( i );Reading a volatile pointer is an observable effect, so the loop cannot disappear. And since the address of the signal escapes to a place the compiler does not control, it can no longer assume that the slot list is still empty, which is exactly the branch being measured.
It costs one read per iteration, and that read is on both sides of the measurement: the floor also pays for it, so that the difference remains only the Emit.
Both compilers now give 0.54 ns.
A check that measures no performance at all was added
Check( dNs > 0.0, "and the emit loop was not removed by the compiler" );It measures whether the measurement happened. It is the only defense against this coming back (a smarter optimizer, a new flag, another compiler), and it costs one comparison.
The state of spec 07, after the audit
event.signal went from 90 to 115 checks. The whole ctest run is 79/79 on Windows x64, Debug and Release.
**115 with the machine idle, 114 with the whole
ctestrunning.** One of the time gates refuses to judge when the floor says the machine is not reliable at that moment, and that design was already here, described in the section on the two intermittent tests. The case is reported, and does not fail.
**The
Removefix and the two new cases were not built on Linux.** The rest of the module was, in the previous batch, including under ASan/UBSan/LSan and TSan. This is stated.
What is still missing:
- the spec asks for the bus dispatch to be verified "by inspecting the generated assembly". What the test requires instead is the property that makes it possible: the type numbers are small, distinct and contiguous. Reading the assembly in a test would be fragile, and that is a declared choice.
- ~~
Compactdoes not cross to the C layer~~ delivered after this was written, with theDeadCountthat was missing on both sides. See its own section above. - the time gates (
< 2 nswith zero slots,< 5 nswith one,< 200 nswith a hundred) still run only outside the sanitizers, which was already stated. CConcurrentSignalhas noConnectWithPriority,Compactor member connection. The spec does not ask for parity (it says it "pays for what it uses"). Even so, the difference was not written down anywhere, and now it is.
---
The state of spec 07, as written in the previous batch
This section is a historical record and was left as written. The audit, described above, came after it and closed the IDispatcher item (see "The dispatcher seam was declared and had never seen an implementation").
| configuration | event.signal | event.cabi | ctest |
|---|---|---|---|
| Linux Debug | n/a | n/a | 59/59 |
| Linux Release | 94 | 34 | n/a |
| Linux ASan/UBSan/LSan | 89, 0 warnings | 34, 0 warnings | n/a |
| Linux TSan | 89, 0 data races | n/a | n/a |
| Windows x64 Debug | 90 | 34 | 55/55 |
| Windows x64 Release | 90 | n/a | n/a |
(89 instead of 94 under a sanitizer because the time gates are not required there.)
What remains to be done:
- ~~the
IDispatcherseam is declared and wired toPost, and a case that exercises it with a real dispatcher is missing~~ delivered in the audit, with a test dispatcher inevent_signal.cpp. - the spec asks for the bus dispatch to be verified "by inspecting the generated assembly". What the test requires instead is the property that makes it possible: the type numbers are small, distinct and contiguous. Reading the assembly in a test would be fragile and hard to maintain, and it was a conscious choice.
- the
eventsection ofsmokeshrank from 164 to 12 checks on purpose. The coverage moved to the dedicated test suite, which covers more and better. The file itself says so.