From 7b2541e35cbca168707b6393a9bc9c7567f014f5 Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 11 May 2019 23:43:54 +0200 Subject: [PATCH] fixed thread bug caused by deleting a thread before it is actually terminated --- libretroshare/src/gxstrans/p3gxstrans.cc | 8 ++++++++ libretroshare/src/util/rsthreads.cc | 2 +- libretroshare/src/util/rsthreads.h | 2 +- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/gxstrans/p3gxstrans.cc b/libretroshare/src/gxstrans/p3gxstrans.cc index 899dcd177..b0fa4b3f0 100644 --- a/libretroshare/src/gxstrans/p3gxstrans.cc +++ b/libretroshare/src/gxstrans/p3gxstrans.cc @@ -533,6 +533,14 @@ void p3GxsTrans::service_tick() for(std::map::const_iterator it(per_user_statistics.begin());it!=per_user_statistics.end();++it) std::cerr << " " << it->first << ": " << it->second.count << " " << it->second.size << std::endl; #endif + // Waiting here is very important because the thread may still be updating its semaphores after setting isDone() to true + // If we delete it during this operation it will corrupt the stack and cause unpredictable errors. + + while(mCleanupThread->isRunning()) + { + std::cerr << "Waiting for mCleanupThread to terminate..." << std::endl; + rstime::rs_usleep(500*1000); + } delete mCleanupThread; mCleanupThread=NULL ; diff --git a/libretroshare/src/util/rsthreads.cc b/libretroshare/src/util/rsthreads.cc index 4d6189d12..297629a43 100644 --- a/libretroshare/src/util/rsthreads.cc +++ b/libretroshare/src/util/rsthreads.cc @@ -66,8 +66,8 @@ void RsThread::go() runloop(); - mHasStoppedSemaphore.set(1); mShouldStopSemaphore.set(0); + mHasStoppedSemaphore.set(1); // last value that we modify because this is interpreted as a signal that the object can be deleted. } void *RsThread::rsthread_init(void* p) { diff --git a/libretroshare/src/util/rsthreads.h b/libretroshare/src/util/rsthreads.h index 6a61a9b4e..d9c82792a 100644 --- a/libretroshare/src/util/rsthreads.h +++ b/libretroshare/src/util/rsthreads.h @@ -247,7 +247,7 @@ public: void start(const std::string &threadName = ""); - // Returns true of the thread is still running. + // Returns true if the thread is still running. bool isRunning();