Revert D4832473: [Folly] Disable EnvUtil::setAsCurrentEnvironment() on platforms...
[folly.git] / folly / CachelinePadded.h
1 /*
2  * Copyright 2017 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
17 #pragma once
18
19 #include <folly/detail/CachelinePaddedImpl.h>
20
21 namespace folly {
22
23 /**
24  * Holds a type T, in addition to enough padding to round the size up to the
25  * next multiple of the false sharing range used by folly.
26  *
27  * If T is standard-layout, then casting a T* you get from this class to a
28  * CachelinePadded<T>* is safe.
29  *
30  * This class handles padding, but imperfectly handles alignment. (Note that
31  * alignment matters for false-sharing: imagine a cacheline size of 64, and two
32  * adjacent 64-byte objects, with the first starting at an offset of 32. The
33  * last 32 bytes of the first object share a cacheline with the first 32 bytes
34  * of the second.). We alignas this class to be at least cacheline-sized, but
35  * it's implementation-defined what that means (since a cacheline is almost
36  * certainly larger than the maximum natural alignment). The following should be
37  * true for recent compilers on common architectures:
38  *
39  * For heap objects, alignment needs to be handled at the allocator level, such
40  * as with posix_memalign (this isn't necessary with jemalloc, which aligns
41  * objects that are a multiple of cacheline size to a cacheline).
42  *
43  * For static and stack objects, the alignment should be obeyed, and no specific
44  * intervention is necessary.
45  */
46 template <typename T>
47 class CachelinePadded {
48  public:
49   template <typename... Args>
50   explicit CachelinePadded(Args&&... args)
51       : impl_(std::forward<Args>(args)...) {}
52
53   CachelinePadded() {}
54
55   T* get() {
56     return &impl_.item;
57   }
58
59   const T* get() const {
60     return &impl_.item;
61   }
62
63   T* operator->() {
64     return get();
65   }
66
67   const T* operator->() const {
68     return get();
69   }
70
71   T& operator*() {
72     return *get();
73   }
74
75   const T& operator*() const {
76     return *get();
77   }
78
79  private:
80   detail::CachelinePaddedImpl<T> impl_;
81 };
82 }