libcoro icon indicating copy to clipboard operation
libcoro copied to clipboard

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

Open YuHuanTin opened this issue 1 year ago • 1 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.

YuHuanTin avatar May 10 '24 13:05 YuHuanTin

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

jbaldwin avatar May 11 '24 18:05 jbaldwin

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.

jbaldwin avatar May 23 '24 23:05 jbaldwin

@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?

jbaldwin avatar Jul 02 '24 19:07 jbaldwin

@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

YuHuanTin avatar Jul 02 '24 23:07 YuHuanTin

No problem, take your time.

jbaldwin avatar Jul 03 '24 01:07 jbaldwin

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

YuHuanTin avatar Jul 05 '24 14:07 YuHuanTin