From d684b359ecf5cdc69678677f99bfa4071ea9ad3f Mon Sep 17 00:00:00 2001
From: Mirko Waechter <mirko.waechter@kit.edu>
Date: Tue, 11 Sep 2018 10:13:36 +0200
Subject: [PATCH] made NJointController cleanup exception safe

---
 .../NJointControllers/NJointController.cpp    | 30 +++++++++++--------
 1 file changed, 18 insertions(+), 12 deletions(-)

diff --git a/source/RobotAPI/components/units/RobotUnit/NJointControllers/NJointController.cpp b/source/RobotAPI/components/units/RobotUnit/NJointControllers/NJointController.cpp
index 45d8f734d..c8ff87492 100644
--- a/source/RobotAPI/components/units/RobotUnit/NJointControllers/NJointController.cpp
+++ b/source/RobotAPI/components/units/RobotUnit/NJointControllers/NJointController.cpp
@@ -295,17 +295,22 @@ namespace armarx
     NJointController::~NJointController()
     {
         // make sure the destructor of the handles does not throw an exception and triggers a termination of the process
-        try
+        ARMARX_DEBUG << "Deleting thread handles";
+        ScopedLock lock(threadHandlesMutex);
+        for (auto& pair : threadHandles)
         {
-            ARMARX_DEBUG << "Deleting thread handles";
-            ScopedLock lock(threadHandlesMutex);
-            for (auto& pair : threadHandles)
+            try
             {
+
                 auto& name = pair.first;
                 auto& handle = pair.second;
-                if (!handle)
+                if (!handle || !handle->isValid())
+                {
+                    ARMARX_VERBOSE << "Thread Handle is NULL or invalid - skipping";
+                    continue;
+                }
+                if (handle->isDetached())
                 {
-                    ARMARX_VERBOSE << "Thread Handle is NULL - skipping";
                     continue;
                 }
                 std::future_status status;
@@ -325,14 +330,15 @@ namespace armarx
                 }
                 while (status != std::future_status::ready);
             }
+            catch (...)
+            {
+                handleExceptions();
+            }
+        }
+
+        threadHandles.clear();
 
-            threadHandles.clear();
 
-        }
-        catch (...)
-        {
-            handleExceptions();
-        }
     }
 
     ControlTargetBase* NJointController::useControlTarget(const std::string& deviceName, const std::string& controlMode)
-- 
GitLab