Feature request to extend possibility of coroutine declaration
Dear Nodepp dev.team! I would like to make feature request of adding new macro function similar to this one:
#define COROUTINE() [=]( int& _state_, ulong& _time_ )
New macro should look like this:
#define COROUTINE2() [&]( int& _state_, ulong& _time_ )
Name COROUTINE2 may be not the best name for it. Most important difference is capture by reference [&] allowing to access referenced values from various levels of { } C++ compound statements higher than declaration of coroutine itself.
P.S. There is one more macro function with [=] near next line after #define COROUTINE() :
#define fn(...) [=]( __VA_ARGS__ )
But looks like it's nowhere used in source code.
Hi Sergiy! Thanks for reaching out and for your interest in improving Nodepp.
Regarding your request to add a macro with reference capture [&], I must decline it. Every design choice in Nodepp — from the internal struct NODE {...}; ptr_t<NODE> obj; to the use of [=] — exists for a strategic reason. The core philosophy of Nodepp is to ensure that asynchronous tasks remain memory-safe without a Garbage Collector.
1. Why [&] is Dangerous in Nodepp
In an event-driven system, coroutines are persistent, but the scopes where they are created are often temporary. If you capture by reference [&], and the original scope is destroyed while the coroutine is suspended (waiting for a timer, a socket, or an event), you will face Undefined Behavior or a Segmentation Fault. The reference will point to "dead" memory.
tcp_t ([=]( socket_t socket ){
// If we used [&] here, 'socket' could be out of scope
// by the time the data actually arrives.
socket.onData([&]( string_t chunk ){
console::log( ">>", chunk.size(), socket.get_fd() ); // CRASH / Illegal Access
});
stream::pipe( socket );
});
2. The Nodepp Way: ptr_t is the Solution
If you need to modify or access large/mutable objects without expensive copies, the correct approach is to wrap them in ptr_t. This ensures the memory stays alive exactly as long as the coroutine needs it.
// Instead of [&], use ptr_t for safe, zero-copy sharing
ptr_t<std::string> data ( 0UL, std::string( "Hello World" ) );
process::add( coroutine::add( COROUTINE() {
coBegin
console::log( *data ); // Safe access, ref-counting handles the rest
coFinish;
}));
Copying a ptr_t is just copying a void* pointer. It is extremely cheap for the CPU and prevents fragmentation. Using ptr_t is how Nodepp maintains its memory safety standard.
However, if you can guarantee the object won't go out of scope (e.g., a global variable), I recommend being explicit by creating a pointer/reference before the coroutine:
int* ref = &global_variable;
process::add( coroutine::add( COROUTINE(){
console::log( ">>", *ref );
return -1;
}));
3. Efficiency: Why type::move and ptr_t beat std:: copies
If your concern is the overhead of std:: copies, type::move is the answer. In Nodepp, we leverage Move Semantics to transfer ownership into the ptr_t infrastructure. This achieves Zero-Copy performance with 100% Memory Safety.
Note: Move semantics are implicit within Nodepp primitives like
array_torstring_tbecause they are built uponptr_t; this is whystruct NODE {...}; ptr_t<NODE> obj;exists.
std::string str = "hello world";
ptr_t<std::string> ptr1 ( 0UL );
*ptr1 = type::move( str ); // Ownership transferred
console::log( *ptr1 );
console::log( str.length() ); // -> 0 (str is now safely empty)
/*----*/
std::vector<int> vec ({ 10, 20, 30 });
ptr_t<int> ptr2 ( 3UL );
type::move( vec.begin(), vec.end(), ptr2.begin() );
// Wrapping a ptr_t into an array_t is cheap for the CPU
console::log( array_t<int>( ptr2 ).join() );
Wrapping a ptr_t into an array_t is cheap because it only copies the reference-counted pointer:
// Internal implementation: No data touched, only pointer assignment
array_t( const ptr_t<T>& argc ) noexcept { buffer = argc; }
4. Essential Limitations and Patterns
Circular References: This is the #1 trade-off of reference counting. If an object (like a socket) captures itself in its own events, you create a memory loop. This is why socket.close() or socket.free() are critical: they manually clear internal events to break the cycle and prevent leaks.
tcp_t ([=]( socket_t socket ){
socket.onData([=]( string_t chunk ){
console::log( ">>", chunk.size(), socket.get_fd() );
});
socket.onDrain([=](){
socket.close(); // this clear internal event to break circular dependency
});
stream::pipe( socket );
});
void free() const noexcept {
if( is_state( STATE::FS_STATE_REUSE ) && !is_feof() && obj.count()>1 ){ return; }
if( is_state( STATE::FS_STATE_KILL ) ) /*-------*/ { return; }
if(!is_state( STATE::FS_STATE_CLOSE | STATE::FS_STATE_REUSE ) )
{ onDrain.emit(); kill(); } else { kill(); }
onUnpipe.clear(); onResume.clear();
onError .clear(); onData .clear();
onOpen .clear(); onPipe .clear(); onClose.emit();
}
Context Binding (type::bind): Capturing this inside a class lambda is dangerous because this is a raw pointer. Use type::bind to wrap the instance in a ptr_t, keeping the class alive as long as the task needs it:
class my_class { public:
int variable = 10;
my_class() {
auto self = type::bind( this ); // Safe reference counting for 'this'
process::add( fn() -> int {
console::log( self->variable ); // 10
self->variable = 20;
console::log( self->variable ); // 20
return -1; });
}
};
5. Conclusion
Adding [&] as a standard macro would invite developers to bypass the safety layers that make Nodepp stable for high-performance, "Green Computing" production. The fn() macro was actually designed to encourage this pattern, We prioritize Robustness and Determinism over syntax convenience. I highly recommend checking our examples to master these patterns.
Best regards, Enmanuel D. Becerra C.
Hi Sergiy,
My apologies if you ran into any compilation errors recently. I was experimenting with a more declarative syntax (fn, async), but after testing it on Wasm, I realized it causes naming collisions and breaks the logic parity that is vital to the project.
I’ve decided to revert these changes and stick to the Nodepp standard: [=] and vanilla syntax. I cannot afford cross-platform disparity for the sake of aesthetics. Thanks for your patience.
Enmanuel.
this was what I was planning to add:
#define GENERATOR(NAME) struct NAME : public nodepp::generator_t
#define COROUTINE() [=]( int& _state_, ulong& _time_ )
#define fn(...) [=]( __VA_ARGS__ )
#define async() COROUTINE()
#define coGenerator(NAME) GENERATOR(NAME)
process::add( coroutine::add( async() -> int {
coBegin
while( true ){ console::log( "hello world!" ); coDelay(1000); }
coFinish
}));
event.on( fn() -> void {
console::log( "event triggered" );
});
but both async() and fn breaks emscripten
This is entire article! Not just an answer. Thank you!
My knowledge of Nodepp was missing ptr_t and type::*