SFML community forums

Help => General => Topic started by: NGM88 on August 27, 2018, 02:56:41 pm

Title: Tcp socket in sf::Thread CPU usage
Post by: NGM88 on August 27, 2018, 02:56:41 pm
Posting in General since it concerns both Network and System.

I'm running a blocking socket (tcp) in an sf::Thread. The program uses 1 percent CPU when I don't run the thread and 30 percent CPU when I do run it. VS Diagnostics show that the function that runs in the thread uses all that extra CPU (see the code for the function). Is this normal or am I doing this wrong?

        while (1)
        {
                sf::Packet packet;

                sf::Int32 code;

                if (Socket.receive(packet) == sf::Socket::Done)
                {
                        packet >> code;
                        PacketCodes.push_back(code);

                        switch (code)
                        {
                                // handle stuff
                        }
                }
        }
 
Title: Re: Tcp socket in sf::Thread CPU usage
Post by: eXpl0it3r on August 27, 2018, 03:41:15 pm
What function and which thread is take all the CPU time?
Title: Re: Tcp socket in sf::Thread CPU usage
Post by: NGM88 on August 27, 2018, 06:04:04 pm
What function and which thread is take all the CPU time?

Well, the program consists of the main thread and one extra thread in which I run the code I posted above.

This extra thread is using almost all of the CPU. More specifically, the CPU usage seems to be divided evenly by:

1 - sf::TcpSocket::receive
2 - sf::Packet::~Packet
3 - sf::Packet::Packet
Title: Re: Tcp socket in sf::Thread CPU usage
Post by: eXpl0it3r on August 27, 2018, 06:33:33 pm
So is it truly blocking? Are you constantly receiving data?
Title: Re: Tcp socket in sf::Thread CPU usage
Post by: NGM88 on August 27, 2018, 06:56:17 pm
So is it truly blocking? Are you constantly receiving data?

OK, I remembered that the server I wrote sends the packets it receives to every other client.

        for (unsigned int i = 0; i < Clients.size(); i++)
        {
                if (Selector.isReady(*Clients[i]))
                {
                        sf::Packet packet;

                        if (Clients[i]->receive(packet) == sf::Socket::Done)
                        {
                                for (unsigned int j = 0; j < Clients.size(); j++)
                                {
                                        if (i != j) { Clients[j]->send(packet); }
                                }
                        }
                }
        }
 

... and upon connecting another client to the server, both clients were using only 1 percent CPU as expected.

So, I guess they have to be constantly receiving data or sf::TcpSocket::receive goes nuts?

Sorry for being a noob, still very new to this network voodoo.