Commit 801d2fb3 authored by Louis Royer's avatar Louis Royer

Avoid starvation

parent 003d7e9d
......@@ -27,8 +27,7 @@ UdpServer::UdpServer(const std::string &address, uint16_t port): sockets{}
int UdpServer::Receive(uint8_t *buffer, size_t bufferSize, int timeoutMs, InetAddress &outPeerAddress)
{
// Use the first socket ready for receiving data
// Warning: this may lead to starvation since there is no round robin implemented yet in `Socket::Select`
// Choose at random a ready socket for receiving data
std::vector<Socket> ws;
return Socket::Select(sockets, ws, timeoutMs).receive(buffer, bufferSize, 0, outPeerAddress);
}
......
......@@ -13,6 +13,7 @@
#include <arpa/inet.h>
#include <netdb.h>
#include <random>
#include <stdexcept>
#include <sys/socket.h>
#include <sys/types.h>
......@@ -273,10 +274,20 @@ Socket Socket::Select(const std::vector<Socket> &readSockets, const std::vector<
std::vector<Socket> rs, ws;
Select(readSockets, writeSockets, rs, ws, timeout);
// Return a socket choosen at random from selection
// to avoid starvation
std::default_random_engine generator;
if (!rs.empty())
return rs[0];
{
std::uniform_int_distribution<int> drs(0, rs.size()-1);
return rs[drs(generator)];
}
if (!ws.empty())
return rs[0];
{
std::uniform_int_distribution<int> dws(0, ws.size()-1);
return rs[dws(generator)];
}
return {};
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment