jbaldwin / libcoro

C++20 coroutine library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can it support spawn coro?

nqf opened this issue · comments

commented
 coro::thread_pool tp; 
void handle(std::string& str, std::function<void(std::string)> cb) {
   coro::spawn(tp, [=] () -> coro::task<void> {
        auto xx = co_await ff();
        cb(xx);
        co_return;
    });
}

https://github.com/jbaldwin/libcoro#thread_pool

It sounds like spawn is a nice wrapper so you don't need to co_await the thread pool on the first line of the coroutine? Probably pretty easy to add if I'm understanding correctly.

commented

You're right, In fact, I expect it to be similar to asio::spawn(https://github.com/chriskohlhoff/asio/blob/master/asio/src/examples/cpp17/coroutines_ts/echo_server.cpp#L68), We can set the Executor manually, It can easily create a coro, And will not block the current thread

I can make this work pretty easily with coro::io_scheduler, it basically supports this via the schedule(coro::task<void>&& task) -> void member function already, it could be adapted to take a std::function<void> as a parameter and make the coroutine internally. This could be a standalone coro::spawn(scheduler, fn) or scheduler.spawn(fn). However, coro::thread_pool doesn't currently have an internal coro::task_container so it doesn't really fit the paradigm... However coro::thread_pool already has an overload of schedule(fn, args) and overload could be made to take std::function<T> in this case. The only thing about this version is that it returns a coro::task<ReturnType> where return type is the functors return type, its not a true detached call.

I suppose coro::thread_pool could add in a coro::task_container and have a detached version of schedule to do the same?