Why should I use coroutine in C/C++

2019-06-12 14:45发布

enter image description here 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条回答
贼婆χ
2楼-- · 2019-06-12 15:40

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.

查看更多
登录 后发表回答