ThreadLock.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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() {
  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_destroy(&m_lock);
  34. }
  35. void ThreadLock::initialize() {
  36. return;
  37. }
  38. void ThreadLock::lock() {
  39. auto ret = pthread_mutex_lock(&m_lock);
  40. if (ret != 0) {
  41. MMKVError("fail to lock %p, ret=%d, errno=%s", &m_lock, ret, strerror(errno));
  42. }
  43. }
  44. void ThreadLock::unlock() {
  45. auto ret = pthread_mutex_unlock(&m_lock);
  46. if (ret != 0) {
  47. MMKVError("fail to unlock %p, ret=%d, errno=%s", &m_lock, ret, strerror(errno));
  48. }
  49. }
  50. void ThreadLock::ThreadOnce(ThreadOnceToken_t *onceToken, void (*callback)()) {
  51. pthread_once(onceToken, callback);
  52. }
  53. } // namespace mmkv
  54. #endif // MMKV_USING_PTHREAD