cobalt
cobalt copied to clipboard
example : thread pool + increase asio threads
I am looking for minimal example:
- dispatch cpu work function on a thread pool
- how to increase asio threads (cobalt is single threaded, but in plain asio additional io threads can be added with
io_threads.emplace_back([&io_main]() { io_main.run(); };)
- Are you thinking about a specific thread-pool?
- What do you mean? Cobalt won't work if you add more threads.
thanks for reply @klemens-morgenstern
- normally there are two options
- using explicit thread pool as in examples
- use another io context work cpu intesive work (switch it when needed and code stays async)
- I was looking for a way to add more threads to main IO and if that would work with cobalt (I have not tried it yet)
background: starting
asio::io_context io_mainin more then one threads will add throughput for the handling. Therefore the question, if cobalt relies on ONE context with one thread or is there a possibility to set custom IO context?
You can just use spawn on a single threaded executor, and you should use cobalt::this_thread::set_executor from within.
boost::cobalt::task<void> my_task()
{
boost::cobalt::this_thread::set_executor(co_await boost::cobalt::this_coro::executor);
// do your work here
}
asio::thread_pool tp;
boost::cobalt::spawn(asio::make_strand(tp), my_task(), asio::detached);
You can also use spawn accross threads with use_op, e.g.:
cobalt::main co_main(int, char**)
{
asio::thread_pool tp;
// run the task on another thread
co_await cobalt::spawn(asio::make_strand(tp), my_task(), cobalt::use_op);
co_return 0;
}
co_main does something very similar, but also connects the signals to cancellations, so that SIGTERM causes a graceful shutdown.