我使用SFML线程,这会占用很高的CPU。
当只有主线程运行时,CPU使用率仅为1%,但是当2个线程运行时,CPU高达25%,3个线程 - 50%等等!
我的CPU有4个核心,所以似乎每个额外的线程都消耗整个核心!
为什么会发生这种情况,1个线程添加25%的CPU?
它与帧速率或sf :: sleep()无关,它们对CPU没有任何影响。
有一个小实验程序可以显示一切。运行此代码时,CPU为25%。 使用addidional线程(注释)时,高达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;
}
请帮我解决这个问题。谢谢!