问题
this image comes from Practical usage of setjmp and longjmp in C.
From my understanding, the coroutine
is two process looks like doing parallelly for human but actually doing a single process for machine.
But using setjmp
& longjmp
I feel very hard to read the code. If need to write the same one. For example process A & B, I will give serval States
to the processes to split them into different pieces(states),
do sequentially like:
Process A
switch (state)
case A1:
if (A1 is done)
do B1
break;
...
Process B
switch (state)
case B1:
if (B1 is done)
do A2
break;
...
I need a reason to support me use setjmp
& longjmp
& coroutine
in C/C++.
What's advantage?
回答1:
setjmp/longjmp()
is rarely used by nowaday programmer. Instead, you should use more powerful boost::coroutine, or my QtNetworkNg. Coroutine is used widely, and mostly, in network programming.
I am the author of QtNetworkNg which provides a stackful coroutine implementation. In the document of QtNetworkNg, I wrote:
The traditional network programming use threads. send()/recv() is blocked, and then the Operating System switch current thread to another ready thread until data arrived. This is very straightforward, and easy for network programming. But threads use heavy resources, thousands of connections may consume many memory. More worst, threads cause data races, data currupt, even crashes.
Coroutine-based paradigm is the now and feature of network programming. Coroutine is light-weight thread which has its own stack, not managed by Operating System but QtNetworkNg. Like thread-based paradigm, send()/recv() is blocked, but switch to another coroutine in the same thread unitl data arrived. Many coroutines can be created at low cost. Because there is only one thread, no locks or other synchoronization is needed. The API is straightforward like thread-based paradigm, but avoid the complexities of using threads.
Besides of that, coroutines can handle state machine and timeline more cleanly. Some online game server use coroutine to handle the interacting between thousands of peers.
来源:https://stackoverflow.com/questions/50383520/why-should-i-use-coroutine-in-c-c