CachelinePadded.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #pragma once
  17. #include <cstddef>
  18. #include <utility>
  19. #include <folly/lang/Align.h>
  20. namespace folly {
  21. /**
  22. * Holds a type T, in addition to enough padding to ensure that it isn't subject
  23. * to false sharing within the range used by folly.
  24. *
  25. * If `sizeof(T) <= alignof(T)` then the inner `T` will be entirely within one
  26. * false sharing range (AKA cache line).
  27. */
  28. template <typename T>
  29. class CachelinePadded {
  30. static_assert(
  31. alignof(T) <= max_align_v,
  32. "CachelinePadded does not support over-aligned types.");
  33. public:
  34. template <typename... Args>
  35. explicit CachelinePadded(Args&&... args)
  36. : inner_(std::forward<Args>(args)...) {}
  37. T* get() {
  38. return &inner_;
  39. }
  40. const T* get() const {
  41. return &inner_;
  42. }
  43. T* operator->() {
  44. return get();
  45. }
  46. const T* operator->() const {
  47. return get();
  48. }
  49. T& operator*() {
  50. return *get();
  51. }
  52. const T& operator*() const {
  53. return *get();
  54. }
  55. private:
  56. static constexpr size_t paddingSize() noexcept {
  57. return hardware_destructive_interference_size -
  58. (alignof(T) % hardware_destructive_interference_size);
  59. }
  60. char paddingPre_[paddingSize()];
  61. T inner_;
  62. char paddingPost_[paddingSize()];
  63. };
  64. } // namespace folly