madmongo1 / blog-new-year-2021

Connection Caching HTTP
Boost Software License 1.0
13 stars 5 forks source link

How to write a function to sync get return value? #6

Closed sukeyisme closed 2 years ago

madmongo1 commented 2 years ago

I need more information to be able to answer your question. Get a return value from what?

sukeyisme commented 2 years ago

net::co_spawn( ioctx.get_executor(), [] { return crawl(); }, net::detached);

This is a async call,If want to get return value sync how to do?

madmongo1 commented 2 years ago

the net::detached completion token is causing the return value to be deliberately discarded. You can get the return value type replacing detached with your own lambda or another completion token such as use_awaitable or use_future

So here's one way:

auto f = net::co_spawn(ioctx.get_executor(), crawl(), asio::use_future);
// f is a std::future
f.get();  // block until the future has a value or error

However, you will want to do this on a different thread to the thread that calls run on the io_context

sukeyisme commented 2 years ago

Yes,will have any problem?

sukeyisme commented 2 years ago

how to replacing detached with your own lambda?

Richard Hodges @.***> 于 2021年11月18日周四 17:51写道:

the net::detached completion token is causing the return value to be deliberately discarded. You can get the return value type replacing detached with your own lambda or another completion token such as use_awaitable or use_future

So here's one way:

auto f = net::co_spawn(ioctx.get_executor(), crawl(), asio::use_future); // f is a std::future f.get(); // block until the future has a value or error

However, you will want to do this on a different thread to the thread that calls run on the io_context

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/madmongo1/blog-new-year-2021/issues/6#issuecomment-972705434, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA4GG7UOLLPXQMLPFPN4TJTUMTEBBANCNFSM5II7ETYQ .