4 ms·
I'm not really experienced with Boost so I'm having a hard time understanding what that snippet does. Is there any example that is completely self-contained (or
by paskozdilar 4y ago
I'm not really experienced with Boost so I'm having a hard time understanding what that snippet does. Is there any example that is completely self-contained (or at least limited to STL)?
- jcelerier 4y agoBoost's io_service (since then renamed as io_context) is an implementation of a thread-safe event queue. Threads can put events in the queue (timer events, asynchronous read and write requests for networking, but one can also just push a generic lambda). This example sets up two timers which will regularly push events in the queue, while two threads processes these events. It's from before c++ had lambdas - nowadays it can be written much more tersely. I'll try to write a short example after when I'm not on my phone - it should be reduceable to 5-6 lines of setup at most
- jcelerier 4y ago=> very dumb example of processing messages from ten threads #include <boost/asio.hpp> #include <atomic> #include <iostream> #include <thread> int main() { boost::asio::io_context io; using work_guard_type = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>; work_guard_type work_guard(io.get_executor()); std::vector<std::jthread> t; for(int i = 0; i < 10; i++) t.emplace_back(std::jthread([&io] { io.run(); })); std::atomic_int counter{}; while(counter < 100) io.post([&] { std::cerr << std::this_thread::get_id() << '\n'; counter++; }); io.stop(); return 0; }