ThreadLock.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Tencent is pleased to support the open source community by making
  3. * MMKV available.
  4. *
  5. * Copyright (C) 2018 THL A29 Limited, a Tencent company.
  6. * All rights reserved.
  7. *
  8. * Licensed under the BSD 3-Clause License (the "License"); you may not use
  9. * this file except in compliance with the License. You may obtain a copy of
  10. * the License at
  11. *
  12. * https://opensource.org/licenses/BSD-3-Clause
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #ifndef MMKV_THREADLOCK_H
  21. #define MMKV_THREADLOCK_H
  22. #ifdef __cplusplus
  23. #include "MMKVPredef.h"
  24. #ifndef MMKV_WIN32
  25. # include <pthread.h>
  26. # define MMKV_USING_PTHREAD 1
  27. #endif
  28. #ifndef MMKV_USING_PTHREAD
  29. # include <atomic>
  30. #endif
  31. namespace mmkv {
  32. #if MMKV_USING_PTHREAD
  33. # define ThreadOnceToken_t pthread_once_t
  34. # define ThreadOnceUninitialized PTHREAD_ONCE_INIT
  35. #else
  36. enum ThreadOnceTokenEnum : int32_t { ThreadOnceUninitialized = 0, ThreadOnceInitializing, ThreadOnceInitialized };
  37. using ThreadOnceToken_t = std::atomic<ThreadOnceTokenEnum>;
  38. #endif
  39. class ThreadLock {
  40. #if MMKV_USING_PTHREAD
  41. pthread_mutex_t m_lock;
  42. #else
  43. CRITICAL_SECTION m_lock;
  44. #endif
  45. public:
  46. ThreadLock();
  47. ~ThreadLock();
  48. void initialize();
  49. void lock();
  50. void unlock();
  51. #ifndef MMKV_WIN32
  52. bool try_lock();
  53. #endif
  54. static void ThreadOnce(ThreadOnceToken_t *onceToken, void (*callback)(void));
  55. #ifdef MMKV_WIN32
  56. static void Sleep(int ms);
  57. #endif
  58. // just forbid it for possibly misuse
  59. explicit ThreadLock(const ThreadLock &other) = delete;
  60. ThreadLock &operator=(const ThreadLock &other) = delete;
  61. };
  62. } // namespace mmkv
  63. #endif
  64. #endif //MMKV_THREADLOCK_H