{"id":105139,"date":"2021-04-22T07:00:00","date_gmt":"2021-04-22T14:00:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/oldnewthing\/?p=105139"},"modified":"2021-04-22T05:59:31","modified_gmt":"2021-04-22T12:59:31","slug":"20210422-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20210422-00\/?p=105139","title":{"rendered":"C++ coroutines: Improving cold-start coroutines which complete synchronously"},"content":{"rendered":"<p>Last time, we learned that <a title=\"C++\" href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20210421-00\/?p=105135\"> the na\u00efve implementation of cold-start coroutines is susceptible to stack build-up<\/a>. What we want is for <code>await_<wbr \/>suspend<\/code> to return <code>false<\/code> if the coroutine completed synchronously. This is tricky because that reintroduces a race condition where the coroutine runs asynchronously and completes at the same time we try to transition from synchronous to asynchronous behavior in the awaiter.<\/p>\n<p>For example, we could try this:<\/p>\n<pre>        auto final_suspend() noexcept\r\n        {\r\n            struct awaiter : std::experimental::suspend_always\r\n            {\r\n                simple_promise_base&amp; self;\r\n                void await_suspend(\r\n                    std::experimental::coroutine_handle&lt;&gt;)\r\n                    const noexcept\r\n                {\r\n                    <span style=\"color: blue;\">if (self.m_waiting()) self.m_waiting();<\/span>\r\n                }\r\n            };\r\n            return awaiter{ {}, *this };\r\n        }\r\n\r\n        auto client_await_suspend(\r\n            std::experimental::coroutine_handle&lt;&gt; handle)\r\n        {\r\n            as_handle().resume();\r\n            <span style=\"color: blue;\">m_waiting = handle;\r\n            return m_holder.is_empty();<\/span>\r\n        }\r\n<\/pre>\n<p>The idea here is that we don&#8217;t register a resumption coroutine handle immediately. Instead, we let the coroutine resume, and if it completes synchronously, its <code>final_<wbr \/>suspend<\/code> resumes the awaiter if one exists. In the case of synchronous completion, there won&#8217;t be an awaiter yet. Back in the awaiter, we register the awaiting coroutine for resumption after the synchronous portion of the awaited-for coroutine finishes, and then we peek at whether it indeed completed synchronously. If so, then we return <code>false<\/code>.<\/p>\n<p>This algorithm doesn&#8217;t work because the coroutine may have continued asynchronously, and the asynchronous completion creates a data race against the awaiter trying to check whether the coroutine completed synchronously.<\/p>\n<p>We&#8217;ll have to bring back the atomic waiter.\u00b9<\/p>\n<p>Return to the version where <code>m_waiting<\/code> was a <code>std::atomic&lt;void*&gt;<\/code>.<\/p>\n<pre>        auto final_suspend() noexcept\r\n        {\r\n            struct awaiter : std::experimental::suspend_always\r\n            {\r\n                simple_promise_base&amp; self;\r\n                void await_suspend(\r\n                    std::experimental::coroutine_handle&lt;&gt;)\r\n                    const noexcept\r\n                {\r\n                    auto waiter = self.m_waiting.exchange(completed_ptr,\r\n                        std::memory_order_acq_rel);\r\n                    if (waiting != abandoned_ptr) self.destroy();\r\n                    <span style=\"color: blue;\">else if (waiting != running_ptr) std::experimental::\r\n                        coroutine_handle&lt;&gt;::from_address(waiting).resume();<\/span>\r\n                }\r\n            };\r\n            return awaiter{ {}, *this };\r\n        }\r\n\r\n        auto client_await_suspend(\r\n            std::experimental::coroutine_handle&lt;&gt; handle)\r\n        {\r\n            as_handle().resume();\r\n            <span style=\"color: blue;\">return m_waiting.exchange(handle.address(),\r\n                std::memory_order_acq_rel) == running_ptr;<\/span>\r\n        }\r\n<\/pre>\n<p>We now have implementations for both cold-start and hot-start coroutines. Next time, we&#8217;ll unify them by using another coroutine trick.<\/p>\n<p>\u00b9 &#8220;Atomic Waiter&#8221; sounds like a failed superhero from the 1950&#8217;s.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Avoiding stack build-up.<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-105139","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>Avoiding stack build-up.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/105139","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=105139"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/105139\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=105139"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=105139"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=105139"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}