Hello, I'm triing to use the sfml thread's, and the folowing basic exemple works perfectly:
void thread_func(__attribute__((unused))int *i)
{
while (1)
{
std::cout << "ça alterne" << std::endl;
sleep(1);
}
}
int main()
{
int i;
i = 5;
sf::Thread thread(&thread_func, &i);
thread.launch();
while (1)
{
std::cout << "ça devrait alterner" << std::endl;
sleep (1);
}
}
But, when i'm triing to do exactly the same thing with a window: create a thread on an event, it stop the main thread. does anyone know why? Is the window use different? Am I doing a stupid and basic mistake?
I've done the following code, not commented, but verry basic: Main.cpp, Game.cpp, Game.hpp
This is the Game.hpp
# include <SFML/Window.hpp>
# include <SFML/Graphics.hpp>
# include <iostream>
# define FRAMERATE 60.f
# define TIMER sf::seconds(1.f / FRAMERATE)
class Game
{
public:
Game();
~Game();
bool init();
void loop();
private:
void myexit();
void update();
void refresh();
void event();
void fps();
private:
sf::Time _time;
sf::Clock _clock;
sf::Clock _clockfps;
sf::RenderWindow _window;
sf::Event _event;
unsigned int _width;
unsigned int _height;
bool _game;
int _frames;
int _fps;
sf::Time _timefps;
};
void thread_func_test(int *i);
the Game.cpp:
#include "Client/Game.hpp"
//#include "Client/Particles.hpp"
Game::Game()
{
_fps = 0;
_width = 800;
_height = 600;
_game = true;
_frames = 0;
}
Game::~Game()
{
}
bool Game::init()
{
//_window.create(sf::VideoMode::getDesktopMode(), "window", sf::Style::Close);
_window.create((sf::VideoMode(_width, _height)), "window", sf::Style::Close);
_window.setActive(false);
return (true);
}
void Game::refresh()
{
_frames++;
_window.display();
}
void thread_func_test(__attribute__((unused))int *i)
{
while (1);
}
void Game::event()
{
while (_window.pollEvent(_event))
{
if (_event.key.code == sf::Keyboard::Escape)
_game = false;
if (_event.type == sf::Event::Closed)
_game = false;
if (_event.mouseButton.button == sf::Mouse::Right)
{
int i = 5;
sf::Thread thread(&thread_func_test, &i);
thread.launch();
}
}
}
void Game::myexit()
{
_window.close();
}
void Game::fps()
{
_timefps += _clockfps.restart();
if (_timefps >= sf::seconds(1.f))
{
_fps = _frames;
std::cout << "fps: " << _fps << std::endl;
_timefps = sf::Time::Zero;
_frames = 0;
}
}
void Game::update()
{
//rien pour le moment je debug;
std::cout << "pouet" << std::endl;
}
void Game::loop()
{
_time = sf::Time::Zero;
while (_game)
{
_time += _clock.restart();
event();
fps();
if (_time >= TIMER)
{
_window.clear();
update();
refresh();
_time = sf::Time::Zero;
}
else
sf::sleep(TIMER - _time);
}
myexit();
}
and the Main.cpp:
#include "Client/Game.hpp"
int main()
{
Game game;
if (game.init())
game.loop();
return (0);
}
I compile with:
-W -Wextra -Wall -Werror -lsfml-system -lsfml-window -lsfml-graphics
The problem is that the main thread is not still running when I click on the right mouse.
Does anyone can help me please?
Thanks you
ps: i just notice that this post should be on the window topic :/