Mutex.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/Mutex.h - Mutex Operating System Concept -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the llvm::sys::Mutex class.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_MUTEX_H
  18. #define LLVM_SUPPORT_MUTEX_H
  19. #include "llvm/Support/Threading.h"
  20. #include <cassert>
  21. #include <mutex>
  22. namespace llvm
  23. {
  24. namespace sys
  25. {
  26. /// SmartMutex - A mutex with a compile time constant parameter that
  27. /// indicates whether this mutex should become a no-op when we're not
  28. /// running in multithreaded mode.
  29. template<bool mt_only>
  30. class SmartMutex {
  31. std::recursive_mutex impl;
  32. unsigned acquired = 0;
  33. public:
  34. bool lock() {
  35. if (!mt_only || llvm_is_multithreaded()) {
  36. impl.lock();
  37. return true;
  38. } else {
  39. // Single-threaded debugging code. This would be racy in
  40. // multithreaded mode, but provides not basic checks in single
  41. // threaded mode.
  42. ++acquired;
  43. return true;
  44. }
  45. }
  46. bool unlock() {
  47. if (!mt_only || llvm_is_multithreaded()) {
  48. impl.unlock();
  49. return true;
  50. } else {
  51. // Single-threaded debugging code. This would be racy in
  52. // multithreaded mode, but provides not basic checks in single
  53. // threaded mode.
  54. assert(acquired && "Lock not acquired before release!");
  55. --acquired;
  56. return true;
  57. }
  58. }
  59. bool try_lock() {
  60. if (!mt_only || llvm_is_multithreaded())
  61. return impl.try_lock();
  62. else return true;
  63. }
  64. };
  65. /// Mutex - A standard, always enforced mutex.
  66. typedef SmartMutex<false> Mutex;
  67. template <bool mt_only>
  68. using SmartScopedLock = std::lock_guard<SmartMutex<mt_only>>;
  69. typedef SmartScopedLock<false> ScopedLock;
  70. }
  71. }
  72. #endif
  73. #ifdef __GNUC__
  74. #pragma GCC diagnostic pop
  75. #endif