2
class UDP_Receiver
{
public:
    udp_receiver((boost::asio::io_service& io_service) :
    idle_work_(io_service_),
    socket_(new boost::asio::ip::udp::socket(io_service))
    {
    }

    void start_receive()
    {
        socket_.async_receive_from(boost::asio::buffer(buffer, buffer.size()), 
                                    remote_endpoint_,
                                    [&](boost::system::error_code const& ec, std::size_t N) 
        {
            if (!ec.value())
            {
                std::unique_ptr<char[]> custom_buffer_ptr(new char[N], std::default_delete<char[]>());
                std::memcopy(custom_buffer, &buffer.data(), N);

                do_custom_stuff(std::move(custom_buffer), N);
            }
        }
    }

private:
    std::array<char, 6000> buffer;
    boost::asio::ip::udp::socket socket_;
    boost::asio::io_service::work idle_work_;
};

int main()
{
  std::size_t numberOfThreads = 2;
  std::vector<std::thread> workerThreads;

  boost::asio::io_service io_service_;

  UDP_Receiver udp_receiver(io_service_);

  for(size_t i = 0; i < numberOfThreads; i++) {
    workerThreads.push_back(std::thread([&] { io_service().run(); }));
  }

  for(auto &thread : workerThreads){
    thread.join();
  }
}

The io_service in my scenario is processed by two threads. Now I investigate the problem that if for example two udp messages are received directly on after another the buffer only holds the last message.

So one message is dropped. Is there a thread-safe way which guarantees that all received udp packets are buffered and memcopyed individually without messages losses?

Is for example stream_buffer the solution?

user3851038
  • 85
  • 1
  • 8
  • The `io_service` is processed by two threads ? Why ? Or do you mean two threads access the object ? Please post a [`MCVE`](https://stackoverflow.com/help/mcve). – Blacktempel Feb 08 '18 at 07:26
  • Hi I update the post to give you a better insight about what I mean with process with two threads. I skip the part how the threads are stopped but this not necessary for my question. – user3851038 Feb 08 '18 at 07:50
  • I see. Have you heard of [`strand`](http://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/io_context__strand.html) ? – Blacktempel Feb 08 '18 at 07:55

1 Answers1

0

Isn't it a better idea to use collection of buffers - something like std::vector<std::array<char, 6000>> bufferCollection and then protect it using locks in start_receive(). This way, you can keep filling it safely. You may use std::map if you want to distinguish buffers with some key.

Aman
  • 696
  • 1
  • 8
  • 26