0

I'm using SFML threads, and this makes very high CPU usage.

When only main thread is running, CPU usage is only 1 %, but when 2 threads run, CPU gets as high as 25 %, 3 threads - 50% and so on!!

My CPU has 4 cores, so it seems that each additional thread consumes the whole core!

Why this happens, with 1 thread adding 25% CPU?

It's nothing related to the framerate or sf::sleep(), they make no effect to CPU.

There's a little experimental program which shows everything. When running this code CPU is 25%. When using addidional threads (commented) then goes as high as 75 %.

#include <iostream>
#include <string>
#include <fstream>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

using namespace std;

sf::RenderWindow window;
sf::Event ev;

bool areEvents=false;
bool Window_Closed=false;


void drawZumthin()
{
for(int i=0; i<4; i++)
{
    sf::CircleShape shape(50);
    shape.setFillColor(sf::Color::Green);
    shape.setPosition(i*100,0);

    window.draw(shape);
}
}

void threadOne(int num)
{
long i=0;
while(1)
{
    if(i==0) cout<<"Thread no. "<<num<<endl;
    //sf::sleep(sf::milliseconds(20));
    i++;
}
}

struct Chunk
{
int type;
int tiles[64];
};

void loadNewChunks()
{
cout<<"Loading Chunks\n";

Chunk chunks[25];

for(int i=0; i<25; i++)
{
    chunks[i].type=i;

    for(int j=0; j<64; j++)
    {
        chunks[i].tiles[j]=j-i;
    }
}
}

void startWind()
{
window.create(sf::VideoMode(400,300),"test");
window.setFramerateLimit(60);

while(window.isOpen())
{
    while(window.pollEvent(ev))
    {
        areEvents=true;

        if(ev.type==sf::Event::Closed)
        {
            window.close();
            Window_Closed=true;
        }
    }

    window.clear();

    drawZumthin();

    window.display();
}
}

void getEvents()
{
cout<<"getEvents started\n";
while(!Window_Closed)
{
    if(areEvents)
    {
        bool newChunk=false;

        if(ev.type==sf::Event::TextEntered)
        {
            if(char(ev.text.unicode)=='w') cout<<"\nUp!\n\n";
            if(char(ev.text.unicode)=='s') cout<<"\nDown!\n\n";
            if(char(ev.text.unicode)=='a') cout<<"\nLeft!\n\n";
            if(char(ev.text.unicode)=='d') cout<<"\nRight!\n\n";

            newChunk=true;
        }

        if(newChunk) loadNewChunks();

        areEvents=false;
    }
}
cout<<"GetEvents Stopped.\n";
}

int main()
{
/*cout<<"Launching experimental threads\n";

sf::Thread thr2(threadOne, 1);
sf::Thread thr3(threadOne, 2);
thr2.launch();
thr3.launch();*/

cout<<"Launching startWind()\n";

sf::Thread thr1(startWind);

thr1.launch();

sf::sleep(sf::seconds(2));

getEvents();

return 0;
}

Please help me with this issue. Thanks!

hakeris1010
  • 285
  • 1
  • 5
  • 12

0 Answers0