简体   繁体   中英

boost asio async_receive_from buffer messages in multi thread scenario

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM