├── .gitignore ├── LICENSE ├── README.md ├── coroutine.h └── test.cc /.gitignore: -------------------------------------------------------------------------------- 1 | /vc/ 2 | main.cc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C++11 single .h asymmetric coroutine implementation 2 | 3 | ### API 4 | 5 | in namespace coroutine: 6 | * routine_t create(std::function f); 7 | * void destroy(routine_t id); 8 | * int resume(routine_t id); 9 | * void yield(); 10 | * TYPE await(TYPE(*f)()); 11 | * TYPE await(func, args); 12 | * routine_t current(); 13 | * class Channel with push()/pop(); 14 | 15 | ### OS 16 | 17 | * Linux 18 | * macOS 19 | * Windows 20 | 21 | ### Demo 22 | 23 | ```cpp 24 | #include "coroutine.h" 25 | #include 26 | #include 27 | 28 | coroutine::Channel channel; 29 | 30 | string async_func() 31 | { 32 | std::this_thread::sleep_for(std::chrono::milliseconds(3000)); 33 | return "22"; 34 | } 35 | 36 | void routine_func1() 37 | { 38 | int i = channel.pop(); 39 | std::cout << i << std::endl; 40 | 41 | i = channel.pop(); 42 | std::cout << i << std::endl; 43 | } 44 | 45 | void routine_func2(int i) 46 | { 47 | std::cout << "20" << std::endl; 48 | coroutine::yield(); 49 | 50 | std::cout << "21" << std::endl; 51 | 52 | //run function async 53 | //yield current routine if result not returned 54 | string str = coroutine::await(async_func); 55 | std::cout << str << std::endl; 56 | } 57 | 58 | void thread_func() 59 | { 60 | //create routine with callback like std::function 61 | coroutine::routine_t rt1 = coroutine::create(routine_func1); 62 | coroutine::routine_t rt2 = coroutine::create(std::bind(routine_func2, 2)); 63 | 64 | std::cout << "00" << std::endl; 65 | coroutine::resume(rt1); 66 | 67 | std::cout << "01" << std::endl; 68 | coroutine::resume(rt2); 69 | 70 | std::cout << "02" << std::endl; 71 | channel.push(10); 72 | 73 | std::cout << "03" << std::endl; 74 | coroutine::resume(rt2); 75 | 76 | std::cout << "04" << std::endl; 77 | channel.push(11); 78 | 79 | std::cout << "05" << std::endl; 80 | 81 | std::this_thread::sleep_for(std::chrono::milliseconds(6000)); 82 | coroutine::resume(rt2); 83 | 84 | //destroy routine, free resouce allocated 85 | //Warning: don't destroy routine by itself 86 | coroutine::destroy(rt1); 87 | coroutine::destroy(rt2); 88 | } 89 | 90 | int main() 91 | { 92 | std::thread t1(thread_func); 93 | std::thread t2([](){ 94 | //unsupport coordinating routine crossing threads 95 | }); 96 | t1.join(); 97 | t2.join(); 98 | return 0; 99 | } 100 | ``` -------------------------------------------------------------------------------- /coroutine.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | #ifndef STDEX_COROUTINE_H_ 21 | #define STDEX_COROUTINE_H_ 22 | 23 | #ifndef STACK_LIMIT 24 | #define STACK_LIMIT (1024*1024) 25 | #endif 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | using ::std::string; 39 | using ::std::wstring; 40 | 41 | #ifdef _MSC_VER 42 | #include 43 | #else 44 | #if defined(__APPLE__) && defined(__MACH__) 45 | #define _XOPEN_SOURCE 46 | #include 47 | #else 48 | #include 49 | #endif 50 | #endif 51 | 52 | namespace coroutine { 53 | 54 | typedef unsigned routine_t; 55 | 56 | #ifdef _MSC_VER 57 | 58 | struct Routine 59 | { 60 | std::function func; 61 | bool finished; 62 | LPVOID fiber; 63 | 64 | Routine(std::function f) 65 | { 66 | func = f; 67 | finished = false; 68 | fiber = nullptr; 69 | } 70 | 71 | ~Routine() 72 | { 73 | DeleteFiber(fiber); 74 | } 75 | }; 76 | 77 | struct Ordinator 78 | { 79 | std::vector routines; 80 | std::list indexes; 81 | routine_t current; 82 | size_t stack_size; 83 | LPVOID fiber; 84 | 85 | Ordinator(size_t ss = STACK_LIMIT) 86 | { 87 | current = 0; 88 | stack_size = ss; 89 | fiber = ConvertThreadToFiber(nullptr); 90 | } 91 | 92 | ~Ordinator() 93 | { 94 | for (auto &routine : routines) 95 | delete routine; 96 | } 97 | }; 98 | 99 | thread_local static Ordinator ordinator; 100 | 101 | inline routine_t create(std::function f) 102 | { 103 | Routine *routine = new Routine(f); 104 | 105 | if (ordinator.indexes.empty()) 106 | { 107 | ordinator.routines.push_back(routine); 108 | return ordinator.routines.size(); 109 | } 110 | else 111 | { 112 | routine_t id = ordinator.indexes.front(); 113 | ordinator.indexes.pop_front(); 114 | assert(ordinator.routines[id-1] == nullptr); 115 | ordinator.routines[id-1] = routine; 116 | return id; 117 | } 118 | } 119 | 120 | inline void destroy(routine_t id) 121 | { 122 | Routine *routine = ordinator.routines[id-1]; 123 | assert(routine != nullptr); 124 | 125 | delete routine; 126 | ordinator.routines[id-1] = nullptr; 127 | ordinator.indexes.push_back(id); 128 | } 129 | 130 | inline void __stdcall entry(LPVOID lpParameter) 131 | { 132 | routine_t id = ordinator.current; 133 | Routine *routine = ordinator.routines[id-1]; 134 | assert(routine != nullptr); 135 | 136 | routine->func(); 137 | 138 | routine->finished = true; 139 | ordinator.current = 0; 140 | 141 | SwitchToFiber(ordinator.fiber); 142 | } 143 | 144 | inline int resume(routine_t id) 145 | { 146 | assert(ordinator.current == 0); 147 | 148 | Routine *routine = ordinator.routines[id-1]; 149 | if (routine == nullptr) 150 | return -1; 151 | 152 | if (routine->finished) 153 | return -2; 154 | 155 | if (routine->fiber == nullptr) 156 | { 157 | routine->fiber = CreateFiber(ordinator.stack_size, entry, 0); 158 | ordinator.current = id; 159 | SwitchToFiber(routine->fiber); 160 | } 161 | else 162 | { 163 | ordinator.current = id; 164 | SwitchToFiber(routine->fiber); 165 | } 166 | 167 | return 0; 168 | } 169 | 170 | inline void yield() 171 | { 172 | routine_t id = ordinator.current; 173 | Routine *routine = ordinator.routines[id-1]; 174 | assert(routine != nullptr); 175 | 176 | ordinator.current = 0; 177 | SwitchToFiber(ordinator.fiber); 178 | } 179 | 180 | inline routine_t current() 181 | { 182 | return ordinator.current; 183 | } 184 | 185 | template 186 | inline typename std::result_of::type 187 | await(Function &&func) 188 | { 189 | auto future = std::async(std::launch::async, func); 190 | std::future_status status = future.wait_for(std::chrono::milliseconds(0)); 191 | 192 | while (status == std::future_status::timeout) 193 | { 194 | if (ordinator.current != 0) 195 | yield(); 196 | 197 | status = future.wait_for(std::chrono::milliseconds(0)); 198 | } 199 | return future.get(); 200 | } 201 | 202 | template 203 | inline typename std::result_of::type 204 | await(Function&& func, Args&&... args) 205 | { 206 | using ResultType = typename std::result_of::type; 207 | std::future future = std::async( 208 | std::launch::async, 209 | std::forward(func), 210 | std::forward(args)... 211 | ); 212 | 213 | std::future_status status = future.wait_for(std::chrono::milliseconds(0)); 214 | 215 | while (status == std::future_status::timeout) 216 | { 217 | if (ordinator.current != 0) 218 | yield(); 219 | 220 | status = future.wait_for(std::chrono::milliseconds(0)); 221 | } 222 | return future.get(); 223 | } 224 | 225 | #else 226 | 227 | struct Routine 228 | { 229 | std::function func; 230 | char *stack; 231 | bool finished; 232 | ucontext_t ctx; 233 | 234 | Routine(std::function f) 235 | { 236 | func = f; 237 | stack = nullptr; 238 | finished = false; 239 | } 240 | 241 | ~Routine() 242 | { 243 | delete[] stack; 244 | } 245 | }; 246 | 247 | struct Ordinator 248 | { 249 | std::vector routines; 250 | std::list indexes; 251 | routine_t current; 252 | size_t stack_size; 253 | ucontext_t ctx; 254 | 255 | inline Ordinator(size_t ss = STACK_LIMIT) 256 | { 257 | current = 0; 258 | stack_size = ss; 259 | } 260 | 261 | inline ~Ordinator() 262 | { 263 | for (auto &routine : routines) 264 | delete routine; 265 | } 266 | }; 267 | 268 | thread_local static Ordinator ordinator; 269 | 270 | inline routine_t create(std::function f) 271 | { 272 | Routine *routine = new Routine(f); 273 | 274 | if (ordinator.indexes.empty()) 275 | { 276 | ordinator.routines.push_back(routine); 277 | return ordinator.routines.size(); 278 | } 279 | else 280 | { 281 | routine_t id = ordinator.indexes.front(); 282 | ordinator.indexes.pop_front(); 283 | assert(ordinator.routines[id-1] == nullptr); 284 | ordinator.routines[id-1] = routine; 285 | return id; 286 | } 287 | } 288 | 289 | inline void destroy(routine_t id) 290 | { 291 | Routine *routine = ordinator.routines[id-1]; 292 | assert(routine != nullptr); 293 | 294 | delete routine; 295 | ordinator.routines[id-1] = nullptr; 296 | } 297 | 298 | inline void entry() 299 | { 300 | routine_t id = ordinator.current; 301 | Routine *routine = ordinator.routines[id-1]; 302 | routine->func(); 303 | 304 | routine->finished = true; 305 | ordinator.current = 0; 306 | ordinator.indexes.push_back(id); 307 | } 308 | 309 | inline int resume(routine_t id) 310 | { 311 | assert(ordinator.current == 0); 312 | 313 | Routine *routine = ordinator.routines[id-1]; 314 | if (routine == nullptr) 315 | return -1; 316 | 317 | if (routine->finished) 318 | return -2; 319 | 320 | if (routine->stack == nullptr) 321 | { 322 | //initializes the structure to the currently active context. 323 | //When successful, getcontext() returns 0 324 | //On error, return -1 and set errno appropriately. 325 | getcontext(&routine->ctx); 326 | 327 | //Before invoking makecontext(), the caller must allocate a new stack 328 | //for this context and assign its address to ucp->uc_stack, 329 | //and define a successor context and assign its address to ucp->uc_link. 330 | routine->stack = new char[ordinator.stack_size]; 331 | routine->ctx.uc_stack.ss_sp = routine->stack; 332 | routine->ctx.uc_stack.ss_size = ordinator.stack_size; 333 | routine->ctx.uc_link = &ordinator.ctx; 334 | ordinator.current = id; 335 | 336 | //When this context is later activated by swapcontext(), the function entry is called. 337 | //When this function returns, the successor context is activated. 338 | //If the successor context pointer is NULL, the thread exits. 339 | makecontext(&routine->ctx, reinterpret_cast(entry), 0); 340 | 341 | //The swapcontext() function saves the current context, 342 | //and then activates the context of another. 343 | swapcontext(&ordinator.ctx, &routine->ctx); 344 | } 345 | else 346 | { 347 | ordinator.current = id; 348 | swapcontext(&ordinator.ctx, &routine->ctx); 349 | } 350 | 351 | return 0; 352 | } 353 | 354 | inline void yield() 355 | { 356 | routine_t id = ordinator.current; 357 | Routine *routine = ordinator.routines[id-1]; 358 | assert(routine != nullptr); 359 | 360 | char *stack_top = routine->stack + ordinator.stack_size; 361 | char stack_bottom = 0; 362 | assert(size_t(stack_top - &stack_bottom) <= ordinator.stack_size); 363 | 364 | ordinator.current = 0; 365 | swapcontext(&routine->ctx , &ordinator.ctx); 366 | } 367 | 368 | inline routine_t current() 369 | { 370 | return ordinator.current; 371 | } 372 | 373 | template 374 | inline typename std::result_of::type 375 | await(Function &&func) 376 | { 377 | auto future = std::async(std::launch::async, func); 378 | std::future_status status = future.wait_for(std::chrono::milliseconds(0)); 379 | 380 | while (status == std::future_status::timeout) 381 | { 382 | if (ordinator.current != 0) 383 | yield(); 384 | 385 | status = future.wait_for(std::chrono::milliseconds(0)); 386 | } 387 | return future.get(); 388 | } 389 | 390 | template 391 | inline typename std::result_of::type 392 | await(Function&& func, Args&&... args) 393 | { 394 | using ResultType = typename std::result_of::type; 395 | std::future future = std::async( 396 | std::launch::async, 397 | std::forward(func), 398 | std::forward(args)... 399 | ); 400 | 401 | std::future_status status = future.wait_for(std::chrono::milliseconds(0)); 402 | 403 | while (status == std::future_status::timeout) 404 | { 405 | if (ordinator.current != 0) 406 | yield(); 407 | 408 | status = future.wait_for(std::chrono::milliseconds(0)); 409 | } 410 | return future.get(); 411 | } 412 | 413 | #endif 414 | 415 | template 416 | class Channel 417 | { 418 | public: 419 | Channel() 420 | { 421 | _taker = 0; 422 | } 423 | 424 | Channel(routine_t id) 425 | { 426 | _taker = id; 427 | } 428 | 429 | inline void consumer(routine_t id) 430 | { 431 | _taker = id; 432 | } 433 | 434 | inline void push(const Type &obj) 435 | { 436 | _list.push_back(obj); 437 | if (_taker && _taker != current()) 438 | resume(_taker); 439 | } 440 | 441 | inline void push(Type &&obj) 442 | { 443 | _list.push_back(std::move(obj)); 444 | if (_taker && _taker != current()) 445 | resume(_taker); 446 | } 447 | 448 | inline Type pop() 449 | { 450 | if (!_taker) 451 | _taker = current(); 452 | 453 | while (_list.empty()) 454 | yield(); 455 | 456 | Type obj = std::move(_list.front()); 457 | _list.pop_front(); 458 | return std::move(obj); 459 | } 460 | 461 | inline void clear() 462 | { 463 | _list.clear(); 464 | } 465 | 466 | inline void touch() 467 | { 468 | if (_taker && _taker != current()) 469 | resume(_taker); 470 | } 471 | 472 | inline size_t size() 473 | { 474 | return _list.size(); 475 | } 476 | 477 | inline bool empty() 478 | { 479 | return _list.empty(); 480 | } 481 | 482 | private: 483 | std::list _list; 484 | routine_t _taker; 485 | }; 486 | 487 | } 488 | #endif //STDEX_COROUTINE_H_ 489 | -------------------------------------------------------------------------------- /test.cc: -------------------------------------------------------------------------------- 1 | #include "coroutine.h" 2 | #include 3 | #include 4 | #include 5 | 6 | coroutine::Channel channel; 7 | 8 | string async_func1(int i, const string b) 9 | { 10 | std::this_thread::sleep_for(std::chrono::milliseconds(1000)); 11 | return b + std::to_string(i); 12 | } 13 | 14 | 15 | void routine_func1() 16 | { 17 | int i = channel.pop(); 18 | std::cout << i << std::endl; 19 | 20 | i = channel.pop(); 21 | std::cout << i << std::endl; 22 | } 23 | 24 | void routine_func2(int i) 25 | { 26 | std::cout << "20" << std::endl; 27 | coroutine::yield(); 28 | 29 | std::cout << "21" << std::endl; 30 | 31 | //run function async 32 | //yield current routine if result not returned 33 | string str0 = coroutine::await(async_func1, 0, "async:"); 34 | std::cout << str0 << std::endl; 35 | 36 | string str1 = coroutine::await(std::bind(async_func1, 1, "async:")); 37 | std::cout << str1 << std::endl; 38 | } 39 | 40 | 41 | //expected: 00, 01, 20, 02, 10, 03, 21, 04, 11, 05, async:0, async:1 42 | void thread_func() 43 | { 44 | //create routine with callback like std::function 45 | coroutine::routine_t rt1 = coroutine::create(routine_func1); 46 | coroutine::routine_t rt2 = coroutine::create(std::bind(routine_func2, 2)); 47 | 48 | std::cout << "00" << std::endl; 49 | coroutine::resume(rt1); 50 | 51 | std::cout << "01" << std::endl; 52 | coroutine::resume(rt2); 53 | 54 | std::cout << "02" << std::endl; 55 | channel.push(10); 56 | 57 | std::cout << "03" << std::endl; 58 | coroutine::resume(rt2); 59 | 60 | std::cout << "04" << std::endl; 61 | channel.push(11); 62 | 63 | std::cout << "05" << std::endl; 64 | 65 | for (int i=0; i<400; i++) 66 | { 67 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); 68 | coroutine::resume(rt2); 69 | } 70 | 71 | //destroy routine, free resouce allocated 72 | //Warning: don't destroy routine by itself 73 | coroutine::destroy(rt1); 74 | coroutine::destroy(rt2); 75 | } 76 | 77 | int main() 78 | { 79 | std::thread t1(thread_func); 80 | std::thread t2([](){ 81 | //coordinating routine does not support cross threading usage 82 | }); 83 | t1.join(); 84 | t2.join(); 85 | return 0; 86 | } --------------------------------------------------------------------------------