From 0e2a21edd2510fedc816cf161c4acfb2963beaff Mon Sep 17 00:00:00 2001
From: Nicolas Pope <nwpope@utu.fi>
Date: Wed, 21 Aug 2019 13:53:39 +0300
Subject: [PATCH] Lock and remove on idle job

---
 components/common/cpp/src/timer.cpp                 | 13 ++++++++-----
 .../rgbd-sources/include/ftl/rgbd/streamer.hpp      |  2 ++
 components/rgbd-sources/src/streamer.cpp            |  3 ++-
 3 files changed, 12 insertions(+), 6 deletions(-)

diff --git a/components/common/cpp/src/timer.cpp b/components/common/cpp/src/timer.cpp
index 1dd0919bb..23de94761 100644
--- a/components/common/cpp/src/timer.cpp
+++ b/components/common/cpp/src/timer.cpp
@@ -61,11 +61,14 @@ static void waitTimePoint() {
 	}
 
 	// Still lots of time so do some idle jobs
-	auto idle_job = jobs[kTimerIdle10].begin();
-	while (idle_job != jobs[kTimerIdle10].end() && msdelay >= 10 && sincelast != mspf) {
-		(*idle_job++).job(now);
-		now = get_time();
-		msdelay = mspf - (now % mspf);
+	{
+		UNIQUE_LOCK(mtx, lk);
+		auto idle_job = jobs[kTimerIdle10].begin();
+		while (idle_job != jobs[kTimerIdle10].end() && msdelay >= 10 && sincelast != mspf) {
+			(*idle_job++).job(now);
+			now = get_time();
+			msdelay = mspf - (now % mspf);
+		}
 	}
 
 	// Spin loop until exact grab time
diff --git a/components/rgbd-sources/include/ftl/rgbd/streamer.hpp b/components/rgbd-sources/include/ftl/rgbd/streamer.hpp
index 3ca7b8574..b387d1fe4 100644
--- a/components/rgbd-sources/include/ftl/rgbd/streamer.hpp
+++ b/components/rgbd-sources/include/ftl/rgbd/streamer.hpp
@@ -130,6 +130,8 @@ class Streamer : public ftl::Configurable {
 	//int64_t last_dropped_;
 	//int drop_count_;
 
+	ftl::timer::TimerHandle timer_job_;
+
 	void _transmit(ftl::rgbd::FrameSet &);
 	void _cleanUp();
 	void _addClient(const std::string &source, int N, int rate, const ftl::UUID &peer, const std::string &dest);
diff --git a/components/rgbd-sources/src/streamer.cpp b/components/rgbd-sources/src/streamer.cpp
index 4758c5821..962da5a37 100644
--- a/components/rgbd-sources/src/streamer.cpp
+++ b/components/rgbd-sources/src/streamer.cpp
@@ -125,6 +125,7 @@ Streamer::Streamer(nlohmann::json &config, Universe *net)
 }
 
 Streamer::~Streamer() {
+	timer_job_.cancel();
 	net_->unbind("find_stream");
 	net_->unbind("list_streams");
 	net_->unbind("source_calibration");
@@ -172,7 +173,7 @@ void Streamer::_addClient(const string &source, int N, int rate, const ftl::UUID
 		if (time_peer_ == ftl::UUID(0)) {
 			time_peer_ = peer;
 
-			ftl::timer::add(ftl::timer::kTimerIdle10, [peer,this](int id) {
+			timer_job_ = ftl::timer::add(ftl::timer::kTimerIdle10, [peer,this](int id) {
 				// Also do a time sync (but should be repeated periodically)
 				auto start = std::chrono::high_resolution_clock::now();
 				int64_t mastertime = net_->call<int64_t>(peer, "__ping__");
-- 
GitLab