Browse Source

Join thread pool at exit to prevent static destruction order issue

Paul-Louis Ageneau 4 years ago
parent
commit
4e3ea69073
2 changed files with 14 additions and 3 deletions
  1. 13 2
      src/threadpool.cpp
  2. 1 1
      src/threadpool.hpp

+ 13 - 2
src/threadpool.cpp

@@ -18,15 +18,26 @@
 
 #include "threadpool.hpp"
 
+#include <cstdlib>
+
+namespace {
+	void joinThreadPoolInstance() {
+		rtc::ThreadPool::Instance().join();
+	}
+}
+
 namespace rtc {
 
 ThreadPool &ThreadPool::Instance() {
-	// Init handles joining on cleanup
 	static ThreadPool *instance = new ThreadPool;
 	return *instance;
 }
 
-ThreadPool::~ThreadPool() { join(); }
+ThreadPool::ThreadPool() {
+	std::atexit(joinThreadPoolInstance);
+}
+
+ThreadPool::~ThreadPool() {}
 
 int ThreadPool::count() const {
 	std::unique_lock lock(mWorkersMutex);

+ 1 - 1
src/threadpool.hpp

@@ -56,7 +56,7 @@ public:
 	auto enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...>;
 
 protected:
-	ThreadPool() = default;
+	ThreadPool();
 	~ThreadPool();
 
 	std::function<void()> dequeue(); // returns null function if joining