如何在C ++中实现Coroutines [英] How do you implement Coroutines in C++
问题描述
我怀疑它可以移植,但有什么解决方案吗?我认为可以通过创建一个备用堆栈,并在功能输入上重置SP,BP和IP,并具有yield保存IP和恢复SP + BP。析构函数和异常安全似乎很棘手,但可解决。
I doubt it can be done portably, but are there any solutions out there? I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP. Destructors and exception safety seem tricky but solvable.
已经完成了吗?是不可能的
Has it been done? Is it impossible?
推荐答案
是的,可以完成所有你需要的是一个小的汇编代码,将调用堆栈移动到堆上新分配的堆栈。
Yes it can be done without a problem. All you need is a little assembly code to move the call stack to a newly allocated stack on the heap.
我会查看 boost :: coroutine 库。
I would look at the boost::coroutine library.
你应该注意的一件事是堆栈溢出。在大多数操作系统溢出堆栈将导致segfault,因为虚拟内存页没有映射。但是,如果你在堆上分配堆栈,你不会得到任何保证。
只要记住这一点。
The one thing that you should watch out for is a stack overflow. On most operating systems overflowing the stack will cause a segfault because virtual memory page is not mapped. However if you allocate the stack on the heap you don't get any guarantee. Just keep that in mind.
这篇关于如何在C ++中实现Coroutines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!