diff --git a/src/utils/waitpid_queue.cc b/src/utils/waitpid_queue.cc index ffe3f7fa..63d047d4 100644 --- a/src/utils/waitpid_queue.cc +++ b/src/utils/waitpid_queue.cc @@ -9,38 +9,37 @@ namespace utils { WaitpidQueue::WaitpidQueue() { m_worker = std::async(std::launch::async, [this]() { - bool is_running = true; auto wait_time = 50ms; - while (is_running) { + while (true) { if (!m_queue.empty()) { auto start_time = std::chrono::steady_clock::now(); - while (!m_wakeup_worker.load(std::memory_order_acquire) && !m_should_shutdown) { - auto elapsed = std::chrono::steady_clock::now() - start_time; - - if (elapsed >= wait_time) - break; + while (std::chrono::steady_clock::now() - start_time < wait_time) { + if (m_should_shutdown.load(std::memory_order_acquire)) + return; std::this_thread::sleep_for(50ms); + + if (m_wakeup_worker.load(std::memory_order_acquire)) + break; } } else { m_wakeup_worker.wait(false, std::memory_order_acquire); - std::this_thread::sleep_for(50ms); } + // Adds a small delay to allow new processes to finish if they're quickly spawned and + // terminated. + std::this_thread::sleep_for(50ms); + std::set queue; { std::lock_guard guard(m_mutex); - if (m_should_shutdown) { - if (m_queue.empty()) - return; - - is_running = false; - } + if (m_should_shutdown) + return; if (m_queue.empty()) throw torrent::internal_error("WaitpidQueue worker thread woke up but queue is empty."); @@ -72,6 +71,7 @@ WaitpidQueue::WaitpidQueue() { }); } +// We don't wait for the worker thread to finish as waitpid isn't needed to be called on shutdown. WaitpidQueue::~WaitpidQueue() { { std::lock_guard guard(m_mutex); @@ -80,8 +80,6 @@ WaitpidQueue::~WaitpidQueue() { m_wakeup_worker.store(true, std::memory_order_release); m_wakeup_worker.notify_all(); - - // m_worker.wait(); } void @@ -93,12 +91,6 @@ WaitpidQueue::close_pid(pid_t pid) { { std::lock_guard guard(m_mutex); - - // if (!m_queue.empty()) { - // m_queue.push_back(pid); - // return; - // } - m_queue.insert(pid); } diff --git a/src/utils/waitpid_queue.h b/src/utils/waitpid_queue.h index 4fef82cd..a441e4cc 100644 --- a/src/utils/waitpid_queue.h +++ b/src/utils/waitpid_queue.h @@ -29,11 +29,11 @@ private: std::mutex m_mutex; std::set m_queue; - bool m_should_shutdown{}; - align_cacheline std::atomic m_wakeup_worker{}; + std::atomic m_should_shutdown{}; + std::atomic m_remaining{}; };