* @brief Check that task priority works as expected with all task submission methods. */
| 2279 | * @brief Check that task priority works as expected with all task submission methods. |
| 2280 | */ |
| 2281 | void check_priority() |
| 2282 | { |
| 2283 | constexpr std::chrono::milliseconds sleep_time(200); |
| 2284 | constexpr std::size_t num_tasks = 10; |
| 2285 | // Set the pool to have only 1 thread, so it can only run 1 task at a time. This will ensure the tasks will be executed in priority order. |
| 2286 | BS::thread_pool<BS::tp::priority | BS::tp::pause> pool(1); |
| 2287 | pool.pause(); |
| 2288 | |
| 2289 | // Create a shuffled list of priorities. |
| 2290 | std::vector<BS::priority_t> priorities; |
| 2291 | priorities.reserve(num_tasks - 1); |
| 2292 | for (std::size_t i = 0; i < num_tasks - 1; ++i) |
| 2293 | priorities.push_back(static_cast<BS::priority_t>((i % 2 == 0) ? random<rand_priority_t>(0, BS::pr::highest) : random<rand_priority_t>(BS::pr::lowest, 0))); |
| 2294 | priorities.push_back(BS::pr::lowest); |
| 2295 | priorities.push_back(0); |
| 2296 | priorities.push_back(BS::pr::highest); |
| 2297 | std::shuffle(priorities.begin(), priorities.end(), std::mt19937_64(std::random_device()())); |
| 2298 | |
| 2299 | // Submit tasks using various methods in random priority order. |
| 2300 | std::vector<BS::priority_t> execution_order; |
| 2301 | std::mutex exec_mutex; |
| 2302 | const auto execute_task_priority = [&execution_order, &exec_mutex](const BS::priority_t priority) |
| 2303 | { |
| 2304 | const std::scoped_lock lock(exec_mutex); |
| 2305 | logln("Task with priority ", static_cast<rand_priority_t>(priority), " executed."); |
| 2306 | execution_order.push_back(priority); |
| 2307 | }; |
| 2308 | const std::vector<std::string_view> functions = {"detach_task", "submit_task", "detach_sequence", "submit_sequence", "detach_loop", "submit_loop", "detach_blocks", "submit_blocks"}; |
| 2309 | for (const BS::priority_t priority : priorities) |
| 2310 | { |
| 2311 | const std::string_view func = functions[random<std::size_t>(0, functions.size() - 1)]; |
| 2312 | logln("Launching ", func, "() with priority ", static_cast<rand_priority_t>(priority), "..."); |
| 2313 | if (func == "detach_task") |
| 2314 | { |
| 2315 | pool.detach_task( |
| 2316 | [priority, &execute_task_priority] |
| 2317 | { |
| 2318 | execute_task_priority(priority); |
| 2319 | }, |
| 2320 | priority); |
| 2321 | } |
| 2322 | else if (func == "submit_task") |
| 2323 | { |
| 2324 | std::ignore = pool.submit_task( |
| 2325 | [priority, &execute_task_priority] |
| 2326 | { |
| 2327 | execute_task_priority(priority); |
| 2328 | }, |
| 2329 | priority); |
| 2330 | } |
| 2331 | else if (func == "detach_sequence") |
| 2332 | { |
| 2333 | pool.detach_sequence( |
| 2334 | 0, 1, |
| 2335 | [priority, &execute_task_priority](std::int64_t) |
| 2336 | { |
| 2337 | execute_task_priority(priority); |
| 2338 | }, |