ThreadLock_Win32.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Tencent is pleased to support the open source community by making
  3. * MMKV available.
  4. *
  5. * Copyright (C) 2019 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. #if !(MMKV_USING_PTHREAD)
  22. # include "MMKVLog.h"
  23. # include <atomic>
  24. # include <cassert>
  25. namespace mmkv {
  26. ThreadLock::ThreadLock() : m_lock{0} {
  27. }
  28. ThreadLock::~ThreadLock() {
  29. DeleteCriticalSection(&m_lock);
  30. }
  31. void ThreadLock::initialize() {
  32. // TODO: a better spin count?
  33. if (!InitializeCriticalSectionAndSpinCount(&m_lock, 1024)) {
  34. MMKVError("fail to init critical section:%d", GetLastError());
  35. }
  36. }
  37. void ThreadLock::lock() {
  38. EnterCriticalSection(&m_lock);
  39. }
  40. void ThreadLock::unlock() {
  41. LeaveCriticalSection(&m_lock);
  42. }
  43. void ThreadLock::ThreadOnce(ThreadOnceToken_t *onceToken, void (*callback)()) {
  44. if (!onceToken || !callback) {
  45. assert(onceToken);
  46. assert(callback);
  47. return;
  48. }
  49. while (true) {
  50. auto expected = ThreadOnceUninitialized;
  51. atomic_compare_exchange_weak(onceToken, &expected, ThreadOnceInitializing);
  52. switch (expected) {
  53. case ThreadOnceInitialized:
  54. return;
  55. case ThreadOnceUninitialized:
  56. callback();
  57. onceToken->store(ThreadOnceInitialized);
  58. return;
  59. case ThreadOnceInitializing: {
  60. // another thread is initializing, let's wait for 1ms
  61. ThreadLock::Sleep(1);
  62. break;
  63. }
  64. default: {
  65. MMKVError("should never happen:%d", expected);
  66. assert(0);
  67. return;
  68. }
  69. }
  70. }
  71. }
  72. void ThreadLock::Sleep(int ms) {
  73. ::Sleep(ms);
  74. }
  75. } // namespace mmkv
  76. #endif // MMKV_USING_PTHREAD