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/Futex.h>
32 namespace folly { namespace test {
35 * DeterministicSchedule coordinates the inter-thread communication of a
36 * set of threads under test, so that despite concurrency the execution is
37 * the same every time. It works by stashing a reference to the schedule
38 * in a thread-local variable, then blocking all but one thread at a time.
40 * In order for DeterministicSchedule to work, it needs to intercept
41 * all inter-thread communication. To do this you should use
42 * DeterministicAtomic<T> instead of std::atomic<T>, create threads
43 * using DeterministicSchedule::thread() instead of the std::thread
44 * constructor, DeterministicSchedule::join(thr) instead of thr.join(),
45 * and access semaphores via the helper functions in DeterministicSchedule.
46 * Locks are not yet supported, although they would be easy to add with
47 * the same strategy as the mapping of sem_wait.
49 * The actual schedule is defined by a function from n -> [0,n). At
50 * each step, the function will be given the number of active threads
51 * (n), and it returns the index of the thread that should be run next.
52 * Invocations of the scheduler function will be serialized, but will
53 * occur from multiple threads. A good starting schedule is uniform(0).
55 class DeterministicSchedule : boost::noncopyable {
58 * Arranges for the current thread (and all threads created by
59 * DeterministicSchedule::thread on a thread participating in this
60 * schedule) to participate in a deterministic schedule.
62 explicit DeterministicSchedule(const std::function<int(int)>& scheduler);
64 /** Completes the schedule. */
65 ~DeterministicSchedule();
68 * Returns a scheduling function that randomly chooses one of the
69 * runnable threads at each step, with no history. This implements
70 * a schedule that is equivalent to one in which the steps between
71 * inter-thread communication are random variables following a poisson
74 static std::function<int(int)> uniform(long seed);
77 * Returns a scheduling function that chooses a subset of the active
78 * threads and randomly chooses a member of the subset as the next
79 * runnable thread. The subset is chosen with size n, and the choice
80 * is made every m steps.
82 static std::function<int(int)> uniformSubset(long seed, int n = 2,
85 /** Obtains permission for the current thread to perform inter-thread
87 static void beforeSharedAccess();
89 /** Releases permission for the current thread to perform inter-thread
91 static void afterSharedAccess();
93 /** Launches a thread that will participate in the same deterministic
94 * schedule as the current thread. */
95 template <typename Func, typename... Args>
96 static inline std::thread thread(Func&& func, Args&&... args) {
97 // TODO: maybe future versions of gcc will allow forwarding to thread
98 auto sched = tls_sched;
99 auto sem = sched ? sched->beforeThreadCreate() : nullptr;
100 auto child = std::thread([=](Args... a) {
101 if (sched) sched->afterThreadCreate(sem);
102 SCOPE_EXIT { if (sched) sched->beforeThreadExit(); };
106 beforeSharedAccess();
107 sched->active_.insert(child.get_id());
113 /** Calls child.join() as part of a deterministic schedule. */
114 static void join(std::thread& child);
116 /** Calls sem_post(sem) as part of a deterministic schedule. */
117 static void post(sem_t* sem);
119 /** Calls sem_trywait(sem) as part of a deterministic schedule, returning
120 * true on success and false on transient failure. */
121 static bool tryWait(sem_t* sem);
123 /** Calls sem_wait(sem) as part of a deterministic schedule. */
124 static void wait(sem_t* sem);
127 static __thread sem_t* tls_sem;
128 static __thread DeterministicSchedule* tls_sched;
130 std::function<int(int)> scheduler_;
131 std::vector<sem_t*> sems_;
132 std::unordered_set<std::thread::id> active_;
134 sem_t* beforeThreadCreate();
135 void afterThreadCreate(sem_t*);
136 void beforeThreadExit();
141 * DeterministicAtomic<T> is a drop-in replacement std::atomic<T> that
142 * cooperates with DeterministicSchedule.
144 template <typename T>
145 struct DeterministicAtomic {
148 DeterministicAtomic() = default;
149 ~DeterministicAtomic() = default;
150 DeterministicAtomic(DeterministicAtomic<T> const &) = delete;
151 DeterministicAtomic<T>& operator= (DeterministicAtomic<T> const &) = delete;
153 constexpr /* implicit */ DeterministicAtomic(T v) noexcept : data(v) {}
155 bool is_lock_free() const noexcept {
156 return data.is_lock_free();
159 bool compare_exchange_strong(
161 std::memory_order mo = std::memory_order_seq_cst) noexcept {
162 DeterministicSchedule::beforeSharedAccess();
163 bool rv = data.compare_exchange_strong(v0, v1, mo);
164 DeterministicSchedule::afterSharedAccess();
168 bool compare_exchange_weak(
170 std::memory_order mo = std::memory_order_seq_cst) noexcept {
171 DeterministicSchedule::beforeSharedAccess();
172 bool rv = data.compare_exchange_weak(v0, v1, mo);
173 DeterministicSchedule::afterSharedAccess();
177 T exchange(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
178 DeterministicSchedule::beforeSharedAccess();
179 T rv = data.exchange(v, mo);
180 DeterministicSchedule::afterSharedAccess();
184 /* implicit */ operator T () const noexcept {
185 DeterministicSchedule::beforeSharedAccess();
187 DeterministicSchedule::afterSharedAccess();
191 T load(std::memory_order mo = std::memory_order_seq_cst) const noexcept {
192 DeterministicSchedule::beforeSharedAccess();
193 T rv = data.load(mo);
194 DeterministicSchedule::afterSharedAccess();
198 T operator= (T v) noexcept {
199 DeterministicSchedule::beforeSharedAccess();
201 DeterministicSchedule::afterSharedAccess();
205 void store(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
206 DeterministicSchedule::beforeSharedAccess();
208 DeterministicSchedule::afterSharedAccess();
211 T operator++ () noexcept {
212 DeterministicSchedule::beforeSharedAccess();
214 DeterministicSchedule::afterSharedAccess();
218 T operator++ (int postDummy) noexcept {
219 DeterministicSchedule::beforeSharedAccess();
221 DeterministicSchedule::afterSharedAccess();
225 T operator-- () noexcept {
226 DeterministicSchedule::beforeSharedAccess();
228 DeterministicSchedule::afterSharedAccess();
232 T operator-- (int postDummy) noexcept {
233 DeterministicSchedule::beforeSharedAccess();
235 DeterministicSchedule::afterSharedAccess();
239 T operator+= (T v) noexcept {
240 DeterministicSchedule::beforeSharedAccess();
242 DeterministicSchedule::afterSharedAccess();
246 T operator-= (T v) noexcept {
247 DeterministicSchedule::beforeSharedAccess();
249 DeterministicSchedule::afterSharedAccess();
253 T operator&= (T v) noexcept {
254 DeterministicSchedule::beforeSharedAccess();
256 DeterministicSchedule::afterSharedAccess();
260 T operator|= (T v) noexcept {
261 DeterministicSchedule::beforeSharedAccess();
263 DeterministicSchedule::afterSharedAccess();
270 namespace folly { namespace detail {
273 bool Futex<test::DeterministicAtomic>::futexWait(uint32_t expected,
277 int Futex<test::DeterministicAtomic>::futexWake(int count, uint32_t wakeMask);