| 65 | //============================================================================= |
| 66 | |
| 67 | class CoroutineRunnerImpl : public CoroutineRunner { |
| 68 | public: |
| 69 | CoroutineRunnerImpl() FL_NOEXCEPT : mMainThreadSema(0) {} |
| 70 | |
| 71 | fl::counting_semaphore<2>& get_main_thread_semaphore() FL_NOEXCEPT override { |
| 72 | return mMainThreadSema; |
| 73 | } |
| 74 | |
| 75 | void enqueue(fl::shared_ptr<CoroutineContext> ctx) FL_NOEXCEPT override { |
| 76 | fl::unique_lock<fl::mutex> lock(mQueueMutex) FL_NOEXCEPT; |
| 77 | mQueue.push(fl::weak_ptr<CoroutineContext>(ctx)); |
| 78 | } |
| 79 | |
| 80 | void stop(fl::shared_ptr<CoroutineContext> ctx) FL_NOEXCEPT override { |
| 81 | if (ctx) { |
| 82 | ctx->set_should_stop(true); |
| 83 | // Wake it so it can check should_stop and exit |
| 84 | ctx->wakeup_semaphore().release(); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // Run the next coroutine using two-phase semaphore handoff. |
| 89 | // Returns true if a job ran, false if queue is empty. |
| 90 | bool run_next_job() FL_NOEXCEPT { |
| 91 | fl::shared_ptr<CoroutineContext> ctx; |
| 92 | |
| 93 | { |
| 94 | fl::unique_lock<fl::mutex> lock(mQueueMutex) FL_NOEXCEPT; |
| 95 | |
| 96 | // Remove expired/completed coroutines from front |
| 97 | while (!mQueue.empty()) { |
| 98 | fl::shared_ptr<CoroutineContext> candidate = mQueue.front().lock(); |
| 99 | if (!candidate || candidate->is_completed()) { |
| 100 | mQueue.pop(); |
| 101 | } else { |
| 102 | break; |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | if (mQueue.empty()) { |
| 107 | return false; |
| 108 | } |
| 109 | |
| 110 | ctx = mQueue.front().lock(); |
| 111 | if (!ctx) { |
| 112 | mQueue.pop(); |
| 113 | return false; |
| 114 | } |
| 115 | mQueue.pop(); |
| 116 | // Re-enqueue at back for next cycle |
| 117 | mQueue.push(fl::weak_ptr<CoroutineContext>(ctx)); |
| 118 | } |
| 119 | |
| 120 | // Two-phase handoff: |
| 121 | // 1. Wake the coroutine |
| 122 | ctx->wakeup_semaphore().release(); |
| 123 | |
| 124 | // 2. Wait for "started" signal (first release from coroutine) |