如何在C中的for循环内实现协程 [英] How to implement coroutine within for loop in c

查看:122
本文介绍了如何在C中的for循环内实现协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是部分代码:

void a()
{
    printf("entering a\n");
    int i;
    for(i = 0; i < 3; i++){
        if(setjmp(a_buf) == 0) {
            printf("A step %d\n", i);
            b();
        } else {
            longjmp(b_buf, 1);
        }
    }
    printf("returning from a\n");
}

void b()
{
    printf("entering b\n");
    int i;
    for(i = 0; i < 5; i++){
        if(setjmp(b_buf) == 0) {
            printf("B step %d\n", i);
            a();
        } else {
            longjmp(a_buf, 1);
        }
    }
    printf("returning from b\n");
}

我有两个过程 a & b 。如何使它们像协程一样工作。
希望他们在执行 A步骤0 然后 B步骤0 然后返回 A步骤1 ...直到全部完成。但是看起来计数器 i 从未改变。

I have two processes a & b. How to make them works as coroutine. Wish them doing A Step 0 then B Step 0 then back to A Step 1... until both finished. But looks like counter i never changed.

推荐答案

您要尝试的内容

引用 C11 ,第§7.13.2.1p2


longjmp 函数恢复在同一程序调用中最近一次调用 setjmp 宏所保存的环境。带有相应的jmp_buf参数。如果没有这样的调用,或者该调用是从另一个执行线程执行的,则,或者包含 setjmp 宏的调用的函数已终止执行,或者如果 setjmp 宏的调用在标识符的范围内,该标识符的类型被不同地修改,并且执行已将该范围留在了该标识符中,则行为是不确定的。

The longjmp function restores the environment saved by the most recent invocation of the setjmp macro in the same invocation of the program with the corresponding jmp_buf argument. If there has been no such invocation, or if the invocation was from another thread of execution, or if the function containing the invocation of the setjmp macro has terminated execution in the interim, or if the invocation of the setjmp macro was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined.

强调矿山

关于什么被视为终止执行:

Regarding what counts as terminated execution:

引用 C11 ,章节§note248


例如,通过执行return语句或由于另一个 longjmp 调用已导致在嵌套调用集中较早的函数中转移到 setjmp 调用。

For example, by executing a return statement or because another longjmp call has caused a transfer to a setjmp invocation in a function earlier in the set of nested calls.

因此,假设您先调用 a(),设置 a_buf 后,ls b()。现在 b()设置 b_buf 并跳回到 a 。此时, b 的执行已终止,并且如果您跳回到 b_buf ,该行为是不确定的。

So, say you call a() first, and it calls b() after setting the a_buf. Now b() sets the b_buf and jumps back to a. At this point b's execution has terminated and if you jump back to b_buf, the behavior is undefined.

一个解决您问题的方法可能是定义函数 a_step() b_step()分别仅执行 a() b()的单个步骤。然后循环调用它们。

One possible solution for your problem could be to define functions a_step() and b_step() which perform just a single step of a() and b() respectively. Then call them alternatively in a loop.

这篇关于如何在C中的for循环内实现协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆