ThreadLock.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. #if MMKV_USING_PTHREAD
  29. #else
  30. # include <atomic>
  31. #endif
  32. namespace mmkv {
  33. #if MMKV_USING_PTHREAD
  34. # define ThreadOnceToken_t pthread_once_t
  35. # define ThreadOnceUninitialized PTHREAD_ONCE_INIT
  36. #else
  37. enum ThreadOnceTokenEnum : int32_t { ThreadOnceUninitialized = 0, ThreadOnceInitializing, ThreadOnceInitialized };
  38. using ThreadOnceToken_t = std::atomic<ThreadOnceTokenEnum>;
  39. #endif
  40. class ThreadLock {
  41. private:
  42. #if MMKV_USING_PTHREAD
  43. pthread_mutex_t m_lock;
  44. #else
  45. CRITICAL_SECTION m_lock;
  46. #endif
  47. public:
  48. ThreadLock();
  49. ~ThreadLock();
  50. void initialize();
  51. void lock();
  52. void unlock();
  53. static void ThreadOnce(ThreadOnceToken_t *onceToken, void (*callback)(void));
  54. #ifdef MMKV_WIN32
  55. static void Sleep(int ms);
  56. #endif
  57. // just forbid it for possibly misuse
  58. explicit ThreadLock(const ThreadLock &other) = delete;
  59. ThreadLock &operator=(const ThreadLock &other) = delete;
  60. };
  61. } // namespace mmkv
  62. #endif
  63. #endif //MMKV_THREADLOCK_H