Hacker News new | past | comments | ask | show | jobs | submit login

here's some documentation on how to do it in C++ with boost in 2008, before go even existed: in this example two threads pull events from a single queue.

https://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tu...

(of course it was possible before)




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)?


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


=> 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;
    }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: