thread_guard.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #pragma once
  6. #include "port/port.h"
  7. #include "rocksdb/rocksdb_namespace.h"
  8. namespace ROCKSDB_NAMESPACE {
  9. // Resource management object for threads that joins the thread upon
  10. // destruction. Has unique ownership of the thread object, so copying it is not
  11. // allowed, while moving it transfers ownership.
  12. class ThreadGuard {
  13. public:
  14. ThreadGuard() = default;
  15. explicit ThreadGuard(port::Thread&& thread) : thread_(std::move(thread)) {}
  16. ThreadGuard(const ThreadGuard&) = delete;
  17. ThreadGuard& operator=(const ThreadGuard&) = delete;
  18. ThreadGuard(ThreadGuard&&) noexcept = default;
  19. ThreadGuard& operator=(ThreadGuard&&) noexcept = default;
  20. ~ThreadGuard() {
  21. if (thread_.joinable()) {
  22. thread_.join();
  23. }
  24. }
  25. const port::Thread& GetThread() const { return thread_; }
  26. port::Thread& GetThread() { return thread_; }
  27. private:
  28. port::Thread thread_;
  29. };
  30. } // namespace ROCKSDB_NAMESPACE