AtomicUtil.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright 2017-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. #pragma once
  17. #include <atomic>
  18. #include <cstdint>
  19. namespace folly {
  20. /**
  21. * Sets a bit at the given index in the binary representation of the integer
  22. * to 1. Returns the previous value of the bit, so true if the bit was not
  23. * changed, false otherwise
  24. *
  25. * On some architectures, using this is more efficient than the corresponding
  26. * std::atomic::fetch_or() with a mask. For example to set the first (least
  27. * significant) bit of an integer, you could do atomic.fetch_or(0b1)
  28. *
  29. * The efficiency win is only visible in x86 (yet) and comes from the
  30. * implementation using the x86 bts instruction when possible.
  31. *
  32. * When something other than std::atomic is passed, the implementation assumed
  33. * incompatibility with this interface and calls Atomic::fetch_or()
  34. */
  35. template <typename Atomic>
  36. bool atomic_fetch_set(
  37. Atomic& atomic,
  38. std::size_t bit,
  39. std::memory_order order = std::memory_order_seq_cst);
  40. /**
  41. * Resets a bit at the given index in the binary representation of the integer
  42. * to 0. Returns the previous value of the bit, so true if the bit was
  43. * changed, false otherwise
  44. *
  45. * This follows the same underlying principle and implementation as
  46. * fetch_set(). Using the optimized implementation when possible and falling
  47. * back to std::atomic::fetch_and() when in debug mode or in an architecture
  48. * where an optimization is not possible
  49. */
  50. template <typename Atomic>
  51. bool atomic_fetch_reset(
  52. Atomic& atomic,
  53. std::size_t bit,
  54. std::memory_order order = std::memory_order_seq_cst);
  55. } // namespace folly
  56. #include <folly/synchronization/AtomicUtil-inl.h>