| // Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| #include "src/storage/lib/background_loop/background_loop.h" | |
| #include <lib/async/cpp/task.h> | |
| #include <lib/async/default.h> | |
| #include <lib/zx/thread.h> | |
| #include <zircon/assert.h> | |
| #include <zircon/syscalls/object.h> | |
| #include <atomic> | |
| #include <string> | |
| #include <string_view> | |
| #include <thread> | |
| namespace storage { | |
| BackgroundLoop::BackgroundLoop(std::string_view thread_name) | |
| : thread_([this, name = std::string(thread_name)] { | |
| if (!name.empty()) { | |
| zx::thread::self()->set_property(ZX_PROP_NAME, name.data(), name.size()); | |
| } | |
| worker_tid_.store(std::this_thread::get_id(), std::memory_order_relaxed); | |
| async_set_default_dispatcher(loop_.dispatcher()); | |
| loop_.Run(); | |
| loop_.Shutdown(); | |
| async_set_default_dispatcher(nullptr); | |
| }) {} | |
| BackgroundLoop::~BackgroundLoop() { Shutdown(); } | |
| void BackgroundLoop::Shutdown() { | |
| if (thread_.joinable()) { | |
| ZX_ASSERT_MSG(std::this_thread::get_id() != thread_.get_id(), | |
| "BackgroundLoop::Shutdown() must not be called from the loop's own thread"); | |
| async::PostTask(loop_.dispatcher(), [this] { Quit(); }); | |
| thread_.join(); | |
| } | |
| } | |
| void BackgroundLoop::Quit() { | |
| ZX_ASSERT_MSG(std::this_thread::get_id() == worker_tid_.load(std::memory_order_relaxed), | |
| "BackgroundLoop::Quit() must only be called from the loop's own thread"); | |
| loop_.Quit(); | |
| } | |
| } // namespace storage |