Mutex.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. }
  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. bool unlock() {
  46. if (!mt_only || llvm_is_multithreaded()) {
  47. impl.unlock();
  48. return true;
  49. }
  50. // Single-threaded debugging code. This would be racy in
  51. // multithreaded mode, but provides not basic checks in single
  52. // threaded mode.
  53. assert(acquired && "Lock not acquired before release!");
  54. --acquired;
  55. return true;
  56. }
  57. bool try_lock() {
  58. if (!mt_only || llvm_is_multithreaded())
  59. return impl.try_lock();
  60. return true;
  61. }
  62. };
  63. /// Mutex - A standard, always enforced mutex.
  64. typedef SmartMutex<false> Mutex;
  65. template <bool mt_only>
  66. using SmartScopedLock = std::lock_guard<SmartMutex<mt_only>>;
  67. typedef SmartScopedLock<false> ScopedLock;
  68. }
  69. }
  70. #endif
  71. #ifdef __GNUC__
  72. #pragma GCC diagnostic pop
  73. #endif