Hello everyone, first post here (sorry if this is the wrong place ^^).
I have 10 CircleShapes in a vector and am now trying to update their fill color from a separate thread. It is not working as expected. In fact, nothing happens.
When I click the left mouse button I want to iterate over my shape objects, one at a time, and change the background color.
I am using a mutex to lock the objects inside the second thread before modifying them and in the main thread before drawing them.
Help is much appreciated.
#include <SFML/Graphics.hpp>
#include <mutex>
#include <thread>
auto myThreadFunc(std::mutex &mtx, std::vector<sf::CircleShape> &circles) -> void
{
for (auto &c : circles)
{
mtx.lock();
c.setFillColor(sf::Color::Green);
mtx.unlock();
// Animation pace
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main()
{
sf::RenderWindow window(sf::VideoMode(2400, 1200), "SFML works!");
std::mutex mtx;
std::vector<sf::CircleShape> circles;
for (auto i = 0; i < 10; i++)
{
auto c = sf::CircleShape(100.f);
c.setFillColor(sf::Color::Cyan);
c.setPosition(i*200.f, 0);
circles.push_back(c);
}
while (window.isOpen())
{
sf::Event e;
while (window.pollEvent(e))
{
if (e.type == sf::Event::Closed)
{
window.close();
}
if (e.type == e.MouseButtonReleased && e.mouseButton.button == sf::Mouse::Left)
{
auto worker = std::thread(myThreadFunc, std::ref(mtx), circles);
worker.detach();
}
}
window.clear(sf::Color::Black);
for (auto &circle : circles)
{
mtx.lock();
window.draw(circle);
mtx.unlock();
}
window.display();
}
return 0;
}