From 2acb74bb4454fc698fb01661d46c96b656bb73c2 Mon Sep 17 00:00:00 2001 From: Benjamin Kraft Date: Tue, 12 Sep 2023 14:16:16 +0200 Subject: [PATCH] using mutex to safely delete pendula --- src/Simulation.cpp | 14 ++++++++++---- src/Simulation.h | 2 ++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Simulation.cpp b/src/Simulation.cpp index 6115a2f..f2f080e 100644 --- a/src/Simulation.cpp +++ b/src/Simulation.cpp @@ -15,10 +15,14 @@ Simulation::Simulation() { }; void Simulation::draw(QPainter *p, int screenSize) { + pendulaMutex.lock(); + double scale = screenSize * 0.95 / size; for (const auto pendulum : pendula) pendulum->draw(p, scale); + + pendulaMutex.unlock(); } void Simulation::update() { @@ -40,12 +44,14 @@ void Simulation::update() { } void Simulation::clearPendula() { - auto deleteLater = pendula; + pendulaMutex.lock(); + + for (auto p : pendula) + delete p; pendula.clear(); pendula.shrink_to_fit(); - QThread::usleep(500000); - for (auto p : deleteLater) - delete p; + + pendulaMutex.unlock(); } void Simulation::addPendula(const std::vector &add) { diff --git a/src/Simulation.h b/src/Simulation.h index 315d764..2f80c4e 100644 --- a/src/Simulation.h +++ b/src/Simulation.h @@ -2,6 +2,7 @@ #include #include #include +#include using namespace std::chrono; @@ -28,6 +29,7 @@ public slots: private slots: void update(); private: + std::mutex pendulaMutex; QTimer * timer; int updateInterval = 17; std::vector pendula;