mutex.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. *
  6. * Copyright (C) 1997-2013, International Business Machines
  7. * Corporation and others. All Rights Reserved.
  8. *
  9. ******************************************************************************
  10. */
  11. //----------------------------------------------------------------------------
  12. // File: mutex.h
  13. //
  14. // Lightweight C++ wrapper for umtx_ C mutex functions
  15. //
  16. // Author: Alan Liu 1/31/97
  17. // History:
  18. // 06/04/97 helena Updated setImplementation as per feedback from 5/21 drop.
  19. // 04/07/1999 srl refocused as a thin wrapper
  20. //
  21. //----------------------------------------------------------------------------
  22. #ifndef MUTEX_H
  23. #define MUTEX_H
  24. #include "unicode/utypes.h"
  25. #include "unicode/uobject.h"
  26. #include "umutex.h"
  27. U_NAMESPACE_BEGIN
  28. /**
  29. * Mutex is a helper class for convenient locking and unlocking of a UMutex.
  30. *
  31. * Creating a local scope Mutex will lock a UMutex, holding the lock until the Mutex
  32. * goes out of scope.
  33. *
  34. * If no UMutex is specified, the ICU global mutex is implied.
  35. *
  36. * For example:
  37. *
  38. * static UMutex myMutex;
  39. *
  40. * void Function(int arg1, int arg2)
  41. * {
  42. * static Object* foo; // Shared read-write object
  43. * Mutex mutex(&myMutex); // or no args for the global lock
  44. * foo->Method();
  45. * // When 'mutex' goes out of scope and gets destroyed here, the lock is released
  46. * }
  47. *
  48. * Note: Do NOT use the form 'Mutex mutex();' as that merely forward-declares a function
  49. * returning a Mutex. This is a common mistake which silently slips through the
  50. * compiler!!
  51. */
  52. class U_COMMON_API Mutex : public UMemory {
  53. public:
  54. Mutex(UMutex *mutex = nullptr) : fMutex(mutex) {
  55. umtx_lock(fMutex);
  56. }
  57. ~Mutex() {
  58. umtx_unlock(fMutex);
  59. }
  60. Mutex(const Mutex &other) = delete; // forbid assigning of this class
  61. Mutex &operator=(const Mutex &other) = delete; // forbid copying of this class
  62. void *operator new(size_t s) = delete; // forbid heap allocation. Locals only.
  63. private:
  64. UMutex *fMutex;
  65. };
  66. U_NAMESPACE_END
  67. #endif //_MUTEX_
  68. //eof