2 * Copyright 2013 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <unordered_set>
24 #include <boost/noncopyable.hpp>
25 #include <semaphore.h>
29 #include <folly/ScopeGuard.h>
30 #include <folly/detail/CacheLocality.h>
31 #include <folly/detail/Futex.h>
33 namespace folly { namespace test {
36 * DeterministicSchedule coordinates the inter-thread communication of a
37 * set of threads under test, so that despite concurrency the execution is
38 * the same every time. It works by stashing a reference to the schedule
39 * in a thread-local variable, then blocking all but one thread at a time.
41 * In order for DeterministicSchedule to work, it needs to intercept
42 * all inter-thread communication. To do this you should use
43 * DeterministicAtomic<T> instead of std::atomic<T>, create threads
44 * using DeterministicSchedule::thread() instead of the std::thread
45 * constructor, DeterministicSchedule::join(thr) instead of thr.join(),
46 * and access semaphores via the helper functions in DeterministicSchedule.
47 * Locks are not yet supported, although they would be easy to add with
48 * the same strategy as the mapping of sem_wait.
50 * The actual schedule is defined by a function from n -> [0,n). At
51 * each step, the function will be given the number of active threads
52 * (n), and it returns the index of the thread that should be run next.
53 * Invocations of the scheduler function will be serialized, but will
54 * occur from multiple threads. A good starting schedule is uniform(0).
56 class DeterministicSchedule : boost::noncopyable {
59 * Arranges for the current thread (and all threads created by
60 * DeterministicSchedule::thread on a thread participating in this
61 * schedule) to participate in a deterministic schedule.
63 explicit DeterministicSchedule(const std::function<int(int)>& scheduler);
65 /** Completes the schedule. */
66 ~DeterministicSchedule();
69 * Returns a scheduling function that randomly chooses one of the
70 * runnable threads at each step, with no history. This implements
71 * a schedule that is equivalent to one in which the steps between
72 * inter-thread communication are random variables following a poisson
75 static std::function<int(int)> uniform(long seed);
78 * Returns a scheduling function that chooses a subset of the active
79 * threads and randomly chooses a member of the subset as the next
80 * runnable thread. The subset is chosen with size n, and the choice
81 * is made every m steps.
83 static std::function<int(int)> uniformSubset(long seed, int n = 2,
86 /** Obtains permission for the current thread to perform inter-thread
88 static void beforeSharedAccess();
90 /** Releases permission for the current thread to perform inter-thread
92 static void afterSharedAccess();
94 /** Launches a thread that will participate in the same deterministic
95 * schedule as the current thread. */
96 template <typename Func, typename... Args>
97 static inline std::thread thread(Func&& func, Args&&... args) {
98 // TODO: maybe future versions of gcc will allow forwarding to thread
99 auto sched = tls_sched;
100 auto sem = sched ? sched->beforeThreadCreate() : nullptr;
101 auto child = std::thread([=](Args... a) {
102 if (sched) sched->afterThreadCreate(sem);
103 SCOPE_EXIT { if (sched) sched->beforeThreadExit(); };
107 beforeSharedAccess();
108 sched->active_.insert(child.get_id());
114 /** Calls child.join() as part of a deterministic schedule. */
115 static void join(std::thread& child);
117 /** Calls sem_post(sem) as part of a deterministic schedule. */
118 static void post(sem_t* sem);
120 /** Calls sem_trywait(sem) as part of a deterministic schedule, returning
121 * true on success and false on transient failure. */
122 static bool tryWait(sem_t* sem);
124 /** Calls sem_wait(sem) as part of a deterministic schedule. */
125 static void wait(sem_t* sem);
128 static __thread sem_t* tls_sem;
129 static __thread DeterministicSchedule* tls_sched;
131 std::function<int(int)> scheduler_;
132 std::vector<sem_t*> sems_;
133 std::unordered_set<std::thread::id> active_;
135 sem_t* beforeThreadCreate();
136 void afterThreadCreate(sem_t*);
137 void beforeThreadExit();
142 * DeterministicAtomic<T> is a drop-in replacement std::atomic<T> that
143 * cooperates with DeterministicSchedule.
145 template <typename T>
146 struct DeterministicAtomic {
149 DeterministicAtomic() = default;
150 ~DeterministicAtomic() = default;
151 DeterministicAtomic(DeterministicAtomic<T> const &) = delete;
152 DeterministicAtomic<T>& operator= (DeterministicAtomic<T> const &) = delete;
154 constexpr /* implicit */ DeterministicAtomic(T v) noexcept : data(v) {}
156 bool is_lock_free() const noexcept {
157 return data.is_lock_free();
160 bool compare_exchange_strong(
162 std::memory_order mo = std::memory_order_seq_cst) noexcept {
163 DeterministicSchedule::beforeSharedAccess();
164 bool rv = data.compare_exchange_strong(v0, v1, mo);
165 DeterministicSchedule::afterSharedAccess();
169 bool compare_exchange_weak(
171 std::memory_order mo = std::memory_order_seq_cst) noexcept {
172 DeterministicSchedule::beforeSharedAccess();
173 bool rv = data.compare_exchange_weak(v0, v1, mo);
174 DeterministicSchedule::afterSharedAccess();
178 T exchange(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
179 DeterministicSchedule::beforeSharedAccess();
180 T rv = data.exchange(v, mo);
181 DeterministicSchedule::afterSharedAccess();
185 /* implicit */ operator T () const noexcept {
186 DeterministicSchedule::beforeSharedAccess();
188 DeterministicSchedule::afterSharedAccess();
192 T load(std::memory_order mo = std::memory_order_seq_cst) const noexcept {
193 DeterministicSchedule::beforeSharedAccess();
194 T rv = data.load(mo);
195 DeterministicSchedule::afterSharedAccess();
199 T operator= (T v) noexcept {
200 DeterministicSchedule::beforeSharedAccess();
202 DeterministicSchedule::afterSharedAccess();
206 void store(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
207 DeterministicSchedule::beforeSharedAccess();
209 DeterministicSchedule::afterSharedAccess();
212 T operator++ () noexcept {
213 DeterministicSchedule::beforeSharedAccess();
215 DeterministicSchedule::afterSharedAccess();
219 T operator++ (int postDummy) noexcept {
220 DeterministicSchedule::beforeSharedAccess();
222 DeterministicSchedule::afterSharedAccess();
226 T operator-- () noexcept {
227 DeterministicSchedule::beforeSharedAccess();
229 DeterministicSchedule::afterSharedAccess();
233 T operator-- (int postDummy) noexcept {
234 DeterministicSchedule::beforeSharedAccess();
236 DeterministicSchedule::afterSharedAccess();
240 T operator+= (T v) noexcept {
241 DeterministicSchedule::beforeSharedAccess();
243 DeterministicSchedule::afterSharedAccess();
247 T operator-= (T v) noexcept {
248 DeterministicSchedule::beforeSharedAccess();
250 DeterministicSchedule::afterSharedAccess();
254 T operator&= (T v) noexcept {
255 DeterministicSchedule::beforeSharedAccess();
257 DeterministicSchedule::afterSharedAccess();
261 T operator|= (T v) noexcept {
262 DeterministicSchedule::beforeSharedAccess();
264 DeterministicSchedule::afterSharedAccess();
271 namespace folly { namespace detail {
274 bool Futex<test::DeterministicAtomic>::futexWait(uint32_t expected,
278 int Futex<test::DeterministicAtomic>::futexWake(int count, uint32_t wakeMask);