1
Système / Du mal avec les threads
« le: Juin 25, 2014, 06:41:34 am »
Salut j'essaie de faire fonctionner une méthode "update" dans un thread.
Je ne sais pas comment m'y prendre.
main.cpp
Game.hpp
En fait ça ne fonctionne pas du tout.. Au lieu d'avoir "while (true)" je devrais avoir "while(window->isOpen())" ou quelque chose du genre.. Je ne sais pas comment.
Je ne sais pas comment m'y prendre.
main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "Game.hpp"
struct Params {
Game g;
sf::RenderWindow *win;
};
int main(void) {
sf::RenderWindow window(sf::VideoMode(800,600), ".");
window.setFramerateLimit(60.f);
Game game;
sf::Thread thread(&Game::update, &game);
thread.launch();
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) window.close();
}
window.clear();
game.render(window);
window.display();
}
thread.terminate();
thread.wait();
return 0;
}
#include <iostream>
#include "Game.hpp"
struct Params {
Game g;
sf::RenderWindow *win;
};
int main(void) {
sf::RenderWindow window(sf::VideoMode(800,600), ".");
window.setFramerateLimit(60.f);
Game game;
sf::Thread thread(&Game::update, &game);
thread.launch();
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) window.close();
}
window.clear();
game.render(window);
window.display();
}
thread.terminate();
thread.wait();
return 0;
}
Game.hpp
#ifndef GAME_HPP
#define GAME_HPP
#include <SFML/Graphics.hpp>
#include <iostream>
class Game {
private:
sf::RectangleShape m_shape;
float angle = 0.f;
public:
Game() {
m_shape.setSize(sf::Vector2f(100.f,100.f));
m_shape.setFillColor(sf::Color::Red);
m_shape.setOrigin(50.f,50.f);
m_shape.setPosition(400,300);
}
void update() {
while (true) {
std::cout << "Update thread!\n";
m_shape.setRotation(angle++);
}
}
void render(sf::RenderTarget &window) {
window.draw(m_shape);
}
};
#endif // GAME_HPP
#define GAME_HPP
#include <SFML/Graphics.hpp>
#include <iostream>
class Game {
private:
sf::RectangleShape m_shape;
float angle = 0.f;
public:
Game() {
m_shape.setSize(sf::Vector2f(100.f,100.f));
m_shape.setFillColor(sf::Color::Red);
m_shape.setOrigin(50.f,50.f);
m_shape.setPosition(400,300);
}
void update() {
while (true) {
std::cout << "Update thread!\n";
m_shape.setRotation(angle++);
}
}
void render(sf::RenderTarget &window) {
window.draw(m_shape);
}
};
#endif // GAME_HPP
En fait ça ne fonctionne pas du tout.. Au lieu d'avoir "while (true)" je devrais avoir "while(window->isOpen())" ou quelque chose du genre.. Je ne sais pas comment.