ThreadLock.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #include "ThreadLock.h"
  21. #include "MMKVLog.h"
  22. #if MMKV_USING_PTHREAD
  23. using namespace std;
  24. namespace mmkv {
  25. ThreadLock::ThreadLock() : m_lock({}) {
  26. pthread_mutexattr_t attr;
  27. pthread_mutexattr_init(&attr);
  28. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  29. pthread_mutex_init(&m_lock, &attr);
  30. pthread_mutexattr_destroy(&attr);
  31. }
  32. ThreadLock::~ThreadLock() {
  33. pthread_mutex_unlock(&m_lock);
  34. pthread_mutex_destroy(&m_lock);
  35. }
  36. void ThreadLock::lock() {
  37. auto ret = pthread_mutex_lock(&m_lock);
  38. if (ret != 0) {
  39. MMKVError("fail to lock %p, ret=%d, errno=%s", &m_lock, ret, strerror(errno));
  40. }
  41. }
  42. void ThreadLock::unlock() {
  43. auto ret = pthread_mutex_unlock(&m_lock);
  44. if (ret != 0) {
  45. MMKVError("fail to unlock %p, ret=%d, errno=%s", &m_lock, ret, strerror(errno));
  46. }
  47. }
  48. bool ThreadLock::try_lock() {
  49. auto ret = pthread_mutex_trylock(&m_lock);
  50. return (ret == 0);
  51. }
  52. void ThreadLock::initialize() {
  53. return;
  54. }
  55. void ThreadLock::ThreadOnce(ThreadOnceToken_t *onceToken, void (*callback)()) {
  56. pthread_once(onceToken, callback);
  57. }
  58. } // namespace mmkv
  59. #endif // MMKV_USING_PTHREAD