From 261d0bc1c3297488645f9abdda22faedbc253fc7 Mon Sep 17 00:00:00 2001
From: Nicolas Pope <nwpope@utu.fi>
Date: Sat, 24 Aug 2019 09:25:52 +0300
Subject: [PATCH] Fix garbage bug using timer job

---
 components/common/cpp/include/ftl/threads.hpp |  2 +-
 components/net/cpp/src/universe.cpp           | 26 +++++++++++--------
 2 files changed, 16 insertions(+), 12 deletions(-)

diff --git a/components/common/cpp/include/ftl/threads.hpp b/components/common/cpp/include/ftl/threads.hpp
index b498ca9d0..69af43b34 100644
--- a/components/common/cpp/include/ftl/threads.hpp
+++ b/components/common/cpp/include/ftl/threads.hpp
@@ -7,7 +7,7 @@
 
 #define POOL_SIZE 10
 
-#define DEBUG_MUTEX
+//#define DEBUG_MUTEX
 #define MUTEX_TIMEOUT 20
 
 #if defined DEBUG_MUTEX
diff --git a/components/net/cpp/src/universe.cpp b/components/net/cpp/src/universe.cpp
index 4d1d00499..034c41f1c 100644
--- a/components/net/cpp/src/universe.cpp
+++ b/components/net/cpp/src/universe.cpp
@@ -1,4 +1,5 @@
 #include <ftl/net/universe.hpp>
+#include <ftl/timer.hpp>
 #include <chrono>
 
 #ifdef WIN32
@@ -54,6 +55,20 @@ Universe::Universe(nlohmann::json &config) :
 	_installBindings();
 
 	LOG(INFO) << "SEND BUFFER SIZE = " << send_size_;
+
+	ftl::timer::add(ftl::timer::kTimerIdle10, [this](int64_t ts) {
+		UNIQUE_LOCK(net_mutex_,lk);
+		if (ftl::pool.n_idle() == ftl::pool.size()) {
+			if (garbage_.size() > 0) LOG(INFO) << "Garbage collection";
+			while (garbage_.size() > 0) {
+				// FIXME: There is possibly still something with a peer pointer
+				// that is causing this throw an exception sometimes?
+				delete garbage_.front();
+				garbage_.pop_front();
+			}
+		}
+		return true;
+	});
 }
 
 Universe::~Universe() {
@@ -184,17 +199,6 @@ void Universe::_installBindings() {
 
 // Note: should be called inside a net lock
 void Universe::_cleanupPeers() {
-
-	if (ftl::pool.n_idle() == ftl::pool.size()) {
-		if (garbage_.size() > 0) LOG(INFO) << "Garbage collection";
-		while (garbage_.size() > 0) {
-			// FIXME: There is possibly still something with a peer pointer
-			// that is causing this throw an exception sometimes?
-			delete garbage_.front();
-			garbage_.pop_front();
-		}
-	}
-
 	auto i = peers_.begin();
 	while (i != peers_.end()) {
 		if (!(*i)->isValid()) {
-- 
GitLab