jbaldwin/libcoro

High CPU usage, when thread_count is greater than the number of tasks

Closed this issue · 6 comments

#include <coro/coro.hpp>

coro::task<int> sleep_for(int seconds) {
    std::this_thread::sleep_for(std::chrono::seconds {seconds});
    co_return 0;
}

coro::task<> wait_for_task(auto &Pool, int delaySeconds) {
    co_await Pool.schedule();
    while (true) {
        co_await sleep_for(delaySeconds);
        std::println("[{}]wait for {} seconds", std::chrono::system_clock::now(), delaySeconds);
    }
    co_return;
}

int main() {
    // cpu high when 'thread_count >= 3'
    coro::thread_pool pool {coro::thread_pool::options {.thread_count = 3}};
    coro::sync_wait(coro::when_all(wait_for_task(pool, 1), wait_for_task(pool, 3)));

    return 0;
}

When two tasks are scheduled to any two threads, the extra threads will occupy the CPU of the entire CPU thread.

Hey, thanks for the bug report, I've been able to reproduce this and trying to figure out how to properly fix it.

I've identified a fix but it uncovered a larger bug in the coro::task_container. I'm trying to figure out how to work through that. I'll post a PR tonight though on the fix I have and possible skip/disable the one test that is broken and try and fix that separately.

@YuHuanTin hi, if you are still interested in a fix for this the PR is up #265. Can you give it a try and make sure it fixes your issue?

@YuHuanTin hi, if you are still interested in a fix for this the PR is up #265. Can you give it a try and make sure it fixes your issue?

Sure, but I'll need a couple days before I can test it, I've been a bit busy lately

No problem, take your time.

Thank you very much, this bug has been fixed. There seems to be performance improvement :)