| 123 | } |
| 124 | |
| 125 | void server_queue::start_loop(int64_t idle_sleep_ms) { |
| 126 | running = true; |
| 127 | time_last_task = ggml_time_ms(); |
| 128 | |
| 129 | constexpr auto max_wait_time = std::chrono::seconds(1); |
| 130 | auto should_sleep = [&]() -> bool { |
| 131 | // caller must hold mutex_tasks |
| 132 | if (idle_sleep_ms < 0) { |
| 133 | return false; |
| 134 | } |
| 135 | int64_t now = ggml_time_ms(); |
| 136 | return (now - time_last_task) >= idle_sleep_ms; |
| 137 | }; |
| 138 | |
| 139 | while (true) { |
| 140 | QUE_DBG("%s", "processing new tasks\n"); |
| 141 | |
| 142 | while (true) { |
| 143 | std::unique_lock<std::mutex> lock(mutex_tasks); |
| 144 | if (!running) { |
| 145 | QUE_DBG("%s", "terminate\n"); |
| 146 | return; |
| 147 | } |
| 148 | if (queue_tasks.empty()) { |
| 149 | lock.unlock(); |
| 150 | break; |
| 151 | } |
| 152 | server_task task = std::move(queue_tasks.front()); |
| 153 | queue_tasks.pop_front(); |
| 154 | lock.unlock(); |
| 155 | |
| 156 | QUE_DBG("processing task, id = %d\n", task.id); |
| 157 | callback_new_task(std::move(task)); |
| 158 | } |
| 159 | // all tasks in the current loop is processed, slots data is now ready |
| 160 | QUE_DBG("%s", "update slots\n"); |
| 161 | |
| 162 | // this will run the main inference process for all slots |
| 163 | callback_update_slots(); |
| 164 | { |
| 165 | // update_slots() may take a while to finish, we need to make sure it's not counted as idle |
| 166 | std::unique_lock<std::mutex> lock(mutex_tasks); |
| 167 | time_last_task = ggml_time_ms(); |
| 168 | } |
| 169 | |
| 170 | QUE_DBG("%s", "waiting for new tasks\n"); |
| 171 | while (true) { |
| 172 | std::unique_lock<std::mutex> lock(mutex_tasks); |
| 173 | if (!running || !queue_tasks.empty()) { |
| 174 | break; // go back to process new tasks or terminate |
| 175 | } |
| 176 | |
| 177 | // no tasks, check for sleeping state |
| 178 | if (should_sleep()) { |
| 179 | QUE_INF("%s", "entering sleeping state\n"); |
| 180 | sleeping = true; |
| 181 | callback_sleeping_state(true); |
| 182 | req_stop_sleeping = false; |