且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中的for循环内实现协程

更新时间:2022-12-13 17:07:41

您要尝试的内容

引用 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.