每次调用
co_await
,只有顶层协同程序被挂起。暂停较低级别,
那一级
必须显式挂起自身。在那一点上,它现在是当前的“顶层”。因此,在每种情况下,只有当前的顶层会被挂起。
将其与一个纯粹假设的堆叠协同程序库进行比较:
//This function will always print the same thread ID.
void secondLevel(int id)
{
while(!toBackgroundThread.poll())
suspend_coroutine();
cout << id << " run on " << this_thread::get_id() << endl;
while(!toBackgroundThread.poll())
suspend_coroutine();
cout << id << " run on " << this_thread::get_id() << endl;
}
void topLevel() {
secondLevel(1);
secondLevel(2);
}
void listen(AsyncQueue& queue) {
while (true) {
if (!queue.poll()) {
this_thread::sleep_for(100ms);
}
}
}
int main() {
thread([]() {
listen(toBackgroundThread);
}).detach();
auto coro = create_coroutine(topLevel);
coro.switch_to();
toMainThread.ready(); //Notes that the main thread is waiting
while (true) {
if (!toMainThread.poll()) {
coro.switch_to();
}
}
};
topLevel
没有任何明确的悬挂机械。然而,每当它调用的任何函数挂起执行时,它的执行都会挂起。由给定函数定义的整个调用堆栈
create_coroutine
它所呼叫的一切都暂停了。这就是堆积如山的连体衣的工作原理。
这就是当涉及到无堆叠协程时所要对比的。在无堆栈版本中,每个需要挂起的函数都必须
具体编码
这样做。因此不再是真正的“通用目的”;它现在特别适用于暂停场景。