Re:Lies we tell ourselves to keep using Golang
by paskozdilar on Friday April 29, 2022 @11:27AM
(#31206372)
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)?
[ Parent
| on HN ]
Re:Lies we tell ourselves to keep using Golang
by jcelerier on Friday April 29, 2022 @12:17PM
(#31207138)
Boost'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
Re:Lies we tell ourselves to keep using Golang
by jcelerier on Saturday April 30, 2022 @09:39AM
(#31215999)
=> 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;
}