Search code examples
c++network-programmingsdlsdl-net

Thread query SDL_Net


Running my listen function in a seperate thread seems to use up a lot of CPU Is it considered ok to use Delays to reduce cpu usage or am I using threads all wrong ?

// Running in a seperate Thread
void Server::listen()
{ 
    while (m_running)
    {
        if (SDLNet_UDP_Recv(m_socket, m_packet) > 0)
        {
              //Handle Packet Function
        }
    }
}

Solution

  • From the SDLNet_UDP_Recv reference

    This is a non-blocking call, meaning if there's no data ready to be received the function will return.

    That means if there's nothing to receive then SDLNet_UDP_Recv will return immediately with 0 and your loop will iterate and call SDLNet_UDP_Recv again which returns 0 and so on. This loop will never sleep of pause, so of course it will use as much CPU as it can.

    A possible solution is indeed to add some kind of delay or sleep in the loop.

    I would suggest something like

    while (m_running)
    {
        int res;
        while (m_running && (res = SDLNet_UDP_Recv(...)) > 0)
        {
            // Handle message
        }
    
        if (res < 0)
        {
            // Handle error
        }
        else if (m_running /* && res == 0 */)
        {
            // Small delay or sleep
        }
    }