MicroLock.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2016-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/MicroLock.h>
  17. #include <thread>
  18. #include <folly/portability/Asm.h>
  19. namespace folly {
  20. void MicroLockCore::lockSlowPath(
  21. uint32_t oldWord,
  22. detail::Futex<>* wordPtr,
  23. uint32_t slotHeldBit,
  24. unsigned maxSpins,
  25. unsigned maxYields) {
  26. uint32_t newWord;
  27. unsigned spins = 0;
  28. uint32_t slotWaitBit = slotHeldBit << 1;
  29. uint32_t needWaitBit = 0;
  30. retry:
  31. if ((oldWord & slotHeldBit) != 0) {
  32. ++spins;
  33. if (spins > maxSpins + maxYields) {
  34. // Somebody appears to have the lock. Block waiting for the
  35. // holder to unlock the lock. We set heldbit(slot) so that the
  36. // lock holder knows to FUTEX_WAKE us.
  37. newWord = oldWord | slotWaitBit;
  38. if (newWord != oldWord) {
  39. if (!wordPtr->compare_exchange_weak(
  40. oldWord,
  41. newWord,
  42. std::memory_order_relaxed,
  43. std::memory_order_relaxed)) {
  44. goto retry;
  45. }
  46. }
  47. detail::futexWait(wordPtr, newWord, slotHeldBit);
  48. needWaitBit = slotWaitBit;
  49. } else if (spins > maxSpins) {
  50. // sched_yield(), but more portable
  51. std::this_thread::yield();
  52. } else {
  53. folly::asm_volatile_pause();
  54. }
  55. oldWord = wordPtr->load(std::memory_order_relaxed);
  56. goto retry;
  57. }
  58. newWord = oldWord | slotHeldBit | needWaitBit;
  59. if (!wordPtr->compare_exchange_weak(
  60. oldWord,
  61. newWord,
  62. std::memory_order_acquire,
  63. std::memory_order_relaxed)) {
  64. goto retry;
  65. }
  66. }
  67. } // namespace folly