Uniot Core
0.8.1
Loading...
Searching...
No Matches
Coroutine.h File Reference

Lightweight cooperative multitasking through coroutines. More...

Go to the source code of this file.

Macros

#define COROUTINE_BEGIN()
 Begins a coroutine function block.
 
#define COROUTINE_YIELD()
 Suspends the coroutine execution and returns control.
 
#define COROUTINE_END()
 Marks the end of a coroutine function.
 

Detailed Description

Lightweight cooperative multitasking through coroutines.

This file implements a simple, stackless coroutine mechanism using macros. Coroutines allow functions to suspend their execution at certain points and resume later from where they left off, which is useful for cooperative multitasking, asynchronous operations, and state machines.

Usage example:

void myCoroutine() {
// Do something
doTask1();
// When resumed, continue from here
doTask2();
doFinalTask();
}
#define COROUTINE_YIELD()
Suspends the coroutine execution and returns control.
Definition Coroutine.h:76
#define COROUTINE_BEGIN()
Begins a coroutine function block.
Definition Coroutine.h:61
#define COROUTINE_END()
Marks the end of a coroutine function.
Definition Coroutine.h:92

Macro Definition Documentation

◆ COROUTINE_BEGIN

#define COROUTINE_BEGIN ( )
Value:
static uint32_t coroutine_state = 0; \
switch (coroutine_state) { \
case 0:

Begins a coroutine function block.

This macro must be placed at the beginning of any function that implements a coroutine. It initializes the coroutine state machine by creating a static variable to track execution position and setting up the switch statement that allows returning to the correct point after yielding.

The static state variable preserves the coroutine's position between calls.

◆ COROUTINE_END

#define COROUTINE_END ( )
Value:
} \
return

Marks the end of a coroutine function.

This macro closes the switch statement opened by COROUTINE_BEGIN() and performs a final return. After this point, the coroutine has completed its execution cycle. When called again, the coroutine will start from the beginning (as the state would be 0).

◆ COROUTINE_YIELD

#define COROUTINE_YIELD ( )
Value:
do { \
coroutine_state = __LINE__; \
return; \
case __LINE__:; \
coroutine_state = 0; \
} while (0)

Suspends the coroutine execution and returns control.

When a coroutine yields, it saves its current line number as the state and returns from the function. The next time the coroutine is called, execution resumes right after this yield point.

After resuming, the state is reset to 0 to ensure proper flow if the coroutine completes and needs to be restarted.