2 This file is part of Valgrind, a dynamic binary instrumentation
5 Copyright (C) 2008-2008 Google Inc
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2 of the
11 License, or (at your option) any later version.
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, see <http://www.gnu.org/licenses/>.
21 The GNU General Public License is contained in the file COPYING.
24 // Author: Konstantin Serebryany <opensource@google.com>
26 // Here we define few simple classes that wrap pthread primitives.
28 // We need this to create unit tests for helgrind (or similar tool)
29 // that will work with different threading frameworks.
31 // If one needs to test helgrind's support for another threading library,
32 // he/she can create a copy of this file and replace pthread_ calls
33 // with appropriate calls to his/her library.
35 // Note, that some of the methods defined here are annotated with
36 // ANNOTATE_* macros defined in dynamic_annotations.h.
38 // DISCLAIMER: the classes defined in this header file
39 // are NOT intended for general use -- only for unit tests.
42 #ifndef THREAD_WRAPPERS_PTHREAD_H
43 #define THREAD_WRAPPERS_PTHREAD_H
46 #include <semaphore.h>
50 #include <limits.h> // INT_MAX
53 #include <libkern/OSAtomic.h>
64 #include "../../drd/drd.h"
65 #define ANNOTATE_NO_OP(arg) do { } while(0)
66 #define ANNOTATE_EXPECT_RACE(addr, descr) \
67 ANNOTATE_BENIGN_RACE_SIZED(addr, 4, "expected race")
68 static inline bool RunningOnValgrind() { return RUNNING_ON_VALGRIND
; }
72 # error "Pleeease, do not define NDEBUG"
76 /// Set this to true if malloc() uses mutex on your platform as this may
77 /// introduce a happens-before arc for a pure happens-before race detector.
78 const bool kMallocUsesMutex
= false;
80 /// Current time in milliseconds.
81 static inline int64_t GetCurrentTimeMillis() {
83 gettimeofday(&now
, NULL
);
84 return now
.tv_sec
* 1000 + now
.tv_usec
/ 1000;
87 /// Copy tv to ts adding offset in milliseconds.
88 static inline void timeval2timespec(timeval
*const tv
,
90 int64_t offset_milli
) {
91 const int64_t ten_9
= 1000000000LL;
92 const int64_t ten_6
= 1000000LL;
93 const int64_t ten_3
= 1000LL;
94 int64_t now_nsec
= (int64_t)tv
->tv_sec
* ten_9
;
95 now_nsec
+= (int64_t)tv
->tv_usec
* ten_3
;
96 int64_t then_nsec
= now_nsec
+ offset_milli
* ten_6
;
97 ts
->tv_sec
= then_nsec
/ ten_9
;
98 ts
->tv_nsec
= then_nsec
% ten_9
;
105 /// helgrind does not (yet) support spin locks, so we annotate them.
111 CHECK(0 == pthread_spin_init(&mu_
, 0));
112 ANNOTATE_RWLOCK_CREATE((void*)&mu_
);
115 ANNOTATE_RWLOCK_DESTROY((void*)&mu_
);
116 CHECK(0 == pthread_spin_destroy(&mu_
));
119 CHECK(0 == pthread_spin_lock(&mu_
));
120 ANNOTATE_RWLOCK_ACQUIRED((void*)&mu_
, 1);
123 ANNOTATE_RWLOCK_RELEASED((void*)&mu_
, 1);
124 CHECK(0 == pthread_spin_unlock(&mu_
));
127 pthread_spinlock_t mu_
;
135 SpinLock() : mu_(OS_SPINLOCK_INIT
) {
136 ANNOTATE_RWLOCK_CREATE((void*)&mu_
);
139 ANNOTATE_RWLOCK_DESTROY((void*)&mu_
);
142 OSSpinLockLock(&mu_
);
143 ANNOTATE_RWLOCK_ACQUIRED((void*)&mu_
, 1);
146 ANNOTATE_RWLOCK_RELEASED((void*)&mu_
, 1);
147 OSSpinLockUnlock(&mu_
);
154 #endif // NO_SPINLOCK
156 /// Just a boolean condition. Used by Mutex::LockWhen and similar.
157 template <typename T
>
160 typedef bool (*func_t
)(void*);
162 Condition(bool (*func
)(T
*), T
* arg
)
163 : func1_(func
), arg_(arg
) {}
165 Condition(bool (*func
)())
166 : func0_(func
), arg_(NULL
) {}
168 bool Eval() const { return func1_
? func1_(arg_
) : func0_(); }
177 /// Wrapper for pthread_mutex_t.
179 /// pthread_mutex_t is *not* a reader-writer lock,
180 /// so the methods like ReaderLock() aren't really reader locks.
181 /// We can not use pthread_rwlock_t because it
182 /// does not work with pthread_cond_t.
184 /// TODO: We still need to test reader locks with this class.
185 /// Implement a mode where pthread_rwlock_t will be used
186 /// instead of pthread_mutex_t (only when not used with CondVar or LockWhen).
189 friend class CondVar
;
192 CHECK(0 == pthread_mutex_init(&mu_
, NULL
));
193 CHECK(0 == pthread_cond_init(&cv_
, NULL
));
194 signal_at_unlock_
= true; // Always signal at Unlock to make
195 // Mutex more friendly to hybrid detectors.
198 CHECK(0 == pthread_cond_destroy(&cv_
));
199 CHECK(0 == pthread_mutex_destroy(&mu_
));
201 void Lock() { CHECK(0 == pthread_mutex_lock(&mu_
));}
202 bool TryLock() { return (0 == pthread_mutex_trylock(&mu_
));}
204 if (signal_at_unlock_
) {
205 CHECK(0 == pthread_cond_signal(&cv_
));
207 CHECK(0 == pthread_mutex_unlock(&mu_
));
209 void ReaderLock() { Lock(); }
210 bool ReaderTryLock() { return TryLock();}
211 void ReaderUnlock() { Unlock(); }
213 template <typename T
>
214 void LockWhen(const Condition
<T
>& cond
) { Lock(); WaitLoop(cond
); }
215 template <typename T
>
216 void ReaderLockWhen(const Condition
<T
>& cond
) { Lock(); WaitLoop(cond
); }
217 template <typename T
>
218 void Await(const Condition
<T
>& cond
) { WaitLoop(cond
); }
220 template <typename T
>
221 bool ReaderLockWhenWithTimeout(const Condition
<T
>& cond
, int millis
)
222 { Lock(); return WaitLoopWithTimeout(cond
, millis
); }
223 template <typename T
>
224 bool LockWhenWithTimeout(const Condition
<T
>& cond
, int millis
)
225 { Lock(); return WaitLoopWithTimeout(cond
, millis
); }
226 template <typename T
>
227 bool AwaitWithTimeout(const Condition
<T
>& cond
, int millis
)
228 { return WaitLoopWithTimeout(cond
, millis
); }
232 template <typename T
>
233 void WaitLoop(const Condition
<T
>& cond
) {
234 signal_at_unlock_
= true;
235 while(cond
.Eval() == false) {
236 pthread_cond_wait(&cv_
, &mu_
);
238 ANNOTATE_CONDVAR_LOCK_WAIT(&cv_
, &mu_
);
241 template <typename T
>
242 bool WaitLoopWithTimeout(const Condition
<T
>& cond
, int millis
) {
244 struct timespec timeout
;
246 gettimeofday(&now
, NULL
);
247 timeval2timespec(&now
, &timeout
, millis
);
249 signal_at_unlock_
= true;
250 while (cond
.Eval() == false && retcode
== 0) {
251 retcode
= pthread_cond_timedwait(&cv_
, &mu_
, &timeout
);
254 ANNOTATE_CONDVAR_LOCK_WAIT(&cv_
, &mu_
);
259 // A hack. cv_ should be the first data member so that
260 // ANNOTATE_CONDVAR_WAIT(&MU, &MU) and ANNOTATE_CONDVAR_SIGNAL(&MU) works.
261 // (See also racecheck_unittest.cc)
264 bool signal_at_unlock_
; // Set to true if Wait was called.
268 class MutexLock
{ // Scoped Mutex Locker/Unlocker
282 /// Wrapper for pthread_cond_t.
285 CondVar() { CHECK(0 == pthread_cond_init(&cv_
, NULL
)); }
286 ~CondVar() { CHECK(0 == pthread_cond_destroy(&cv_
)); }
287 void Wait(Mutex
*mu
) { CHECK(0 == pthread_cond_wait(&cv_
, &mu
->mu_
)); }
288 bool WaitWithTimeout(Mutex
*mu
, int millis
) {
290 struct timespec timeout
;
291 gettimeofday(&now
, NULL
);
292 timeval2timespec(&now
, &timeout
, millis
);
293 return 0 != pthread_cond_timedwait(&cv_
, &mu
->mu_
, &timeout
);
295 void Signal() { CHECK(0 == pthread_cond_signal(&cv_
)); }
296 void SignalAll() { CHECK(0 == pthread_cond_broadcast(&cv_
)); }
302 // pthreads do not allow to use condvar with rwlock so we can't make
303 // ReaderLock method of Mutex to be the real rw-lock.
304 // So, we need a special lock class to test reader locks.
305 #define NEEDS_SEPERATE_RW_LOCK
308 RWLock() { CHECK(0 == pthread_rwlock_init(&mu_
, NULL
)); }
309 ~RWLock() { CHECK(0 == pthread_rwlock_destroy(&mu_
)); }
310 void Lock() { CHECK(0 == pthread_rwlock_wrlock(&mu_
)); }
311 void ReaderLock() { CHECK(0 == pthread_rwlock_rdlock(&mu_
)); }
312 void Unlock() { CHECK(0 == pthread_rwlock_unlock(&mu_
)); }
313 void ReaderUnlock() { CHECK(0 == pthread_rwlock_unlock(&mu_
)); }
315 pthread_cond_t dummy
; // Damn, this requires some redesign...
316 pthread_rwlock_t mu_
;
319 class ReaderLockScoped
{ // Scoped RWLock Locker/Unlocker
321 ReaderLockScoped(RWLock
*mu
)
325 ~ReaderLockScoped() {
332 class WriterLockScoped
{ // Scoped RWLock Locker/Unlocker
334 WriterLockScoped(RWLock
*mu
)
338 ~WriterLockScoped() {
348 /// Wrapper for pthread_create()/pthread_join().
351 MyThread(void* (*worker
)(void *), void *arg
= NULL
, const char *name
= NULL
)
352 :wpvpv_(worker
), wvv_(), wvpv_(), arg_(arg
), name_(name
) {}
353 MyThread(void (*worker
)(void), void *arg
= NULL
, const char *name
= NULL
)
354 :wpvpv_(), wvv_(worker
), wvpv_(), arg_(arg
), name_(name
) {}
355 MyThread(void (*worker
)(void *), void *arg
= NULL
, const char *name
= NULL
)
356 :wpvpv_(), wvv_(), wvpv_(worker
), arg_(arg
), name_(name
) {}
358 void Start() { CHECK(0 == pthread_create(&t_
, NULL
, ThreadBody
, this));}
359 void Join() { CHECK(0 == pthread_join(t_
, NULL
));}
360 pthread_t
tid() const { return t_
; }
362 static void *ThreadBody(void *arg
) {
363 MyThread
*my_thread
= reinterpret_cast<MyThread
*>(arg
);
364 if (my_thread
->name_
) {
365 ANNOTATE_THREAD_NAME(my_thread
->name_
);
367 if (my_thread
->wpvpv_
)
368 return my_thread
->wpvpv_(my_thread
->arg_
);
369 if (my_thread
->wvpv_
)
370 my_thread
->wvpv_(my_thread
->arg_
);
376 void *(*wpvpv_
)(void*);
378 void (*wvpv_
)(void*);
384 /// Just a message queue.
385 class ProducerConsumerQueue
{
387 ProducerConsumerQueue(int unused
) {
388 //ANNOTATE_PCQ_CREATE(this);
390 ~ProducerConsumerQueue() {
392 //ANNOTATE_PCQ_DESTROY(this);
396 void Put(void *item
) {
399 ANNOTATE_CONDVAR_SIGNAL(&mu_
); // LockWhen in Get()
400 //ANNOTATE_PCQ_PUT(this);
405 // Blocks if the queue is empty.
407 mu_
.LockWhen(Condition
<typeof(q_
)>(IsQueueNotEmpty
, &q_
));
409 bool ok
= TryGetInternal(&item
);
415 // If queue is not empty,
416 // remove an element from queue, put it into *res and return true.
417 // Otherwise return false.
418 bool TryGet(void **res
) {
420 bool ok
= TryGetInternal(res
);
427 std::queue
<void*> q_
; // protected by mu_
430 bool TryGetInternal(void ** item_ptr
) {
433 *item_ptr
= q_
.front();
435 //ANNOTATE_PCQ_GET(this);
439 static bool IsQueueNotEmpty(std::queue
<void*> * queue
) {
440 return !queue
->empty();
446 /// Function pointer with zero, one or two parameters.
448 typedef void (*F0
)();
449 typedef void (*F1
)(void *arg1
);
450 typedef void (*F2
)(void *arg1
, void *arg2
);
459 } else if (n_params
== 1) {
462 CHECK(n_params
== 2);
463 (F2(f
))(param1
, param2
);
469 Closure
*NewCallback(void (*f
)()) {
470 Closure
*res
= new Closure
;
479 Closure
*NewCallback(void (*f
)(P1
), P1 p1
) {
480 CHECK(sizeof(P1
) <= sizeof(void*));
481 Closure
*res
= new Closure
;
484 res
->param1
= (void*)p1
;
489 template <class T
, class P1
, class P2
>
490 Closure
*NewCallback(void (*f
)(P1
, P2
), P1 p1
, P2 p2
) {
491 CHECK(sizeof(P1
) <= sizeof(void*));
492 Closure
*res
= new Closure
;
495 res
->param1
= (void*)p1
;
496 res
->param2
= (void*)p2
;
500 /*! A thread pool that uses ProducerConsumerQueue.
503 ThreadPool pool(n_workers);
505 pool.Add(NewCallback(func_with_no_args));
506 pool.Add(NewCallback(func_with_one_arg, arg));
507 pool.Add(NewCallback(func_with_two_args, arg1, arg2));
508 ... // more calls to pool.Add()
510 // the ~ThreadPool() is called: we wait workers to finish
511 // and then join all threads in the pool.
516 //! Create n_threads threads, but do not start.
517 explicit ThreadPool(int n_threads
)
519 for (int i
= 0; i
< n_threads
; i
++) {
520 MyThread
*thread
= new MyThread(&ThreadPool::Worker
, this);
521 workers_
.push_back(thread
);
525 //! Start all threads.
526 void StartWorkers() {
527 for (size_t i
= 0; i
< workers_
.size(); i
++) {
528 workers_
[i
]->Start();
533 void Add(Closure
*closure
) {
537 int num_threads() { return workers_
.size();}
539 //! Wait workers to finish, then join all threads.
541 for (size_t i
= 0; i
< workers_
.size(); i
++) {
544 for (size_t i
= 0; i
< workers_
.size(); i
++) {
550 std::vector
<MyThread
*> workers_
;
551 ProducerConsumerQueue queue_
;
553 static void *Worker(void *p
) {
554 ThreadPool
*pool
= reinterpret_cast<ThreadPool
*>(p
);
556 Closure
*closure
= reinterpret_cast<Closure
*>(pool
->queue_
.Get());
557 if(closure
== NULL
) {
566 /// Wrapper for pthread_barrier_t.
569 explicit Barrier(int n_threads
) {CHECK(0 == pthread_barrier_init(&b_
, 0, n_threads
));}
570 ~Barrier() {CHECK(0 == pthread_barrier_destroy(&b_
));}
572 // helgrind 3.3.0 does not have an interceptor for barrier.
573 // but our current local version does.
574 // ANNOTATE_CONDVAR_SIGNAL(this);
575 pthread_barrier_wait(&b_
);
576 // ANNOTATE_CONDVAR_WAIT(this, this);
579 pthread_barrier_t b_
;
584 class BlockingCounter
{
586 explicit BlockingCounter(int initial_count
) :
587 count_(initial_count
) {}
588 bool DecrementCount() {
589 MutexLock
lock(&mu_
);
594 mu_
.LockWhen(Condition
<int>(&IsZero
, &count_
));
598 static bool IsZero(int *arg
) { return *arg
== 0; }
603 int AtomicIncrement(volatile int *value
, int increment
);
606 inline int AtomicIncrement(volatile int *value
, int increment
) {
607 return __sync_add_and_fetch(value
, increment
);
612 inline int AtomicIncrement(volatile int *value
, int increment
) {
613 return OSAtomicAdd32(increment
, value
);
616 // TODO(timurrrr) this is a hack
617 #define memalign(A,B) malloc(B)
619 // TODO(timurrrr) this is a hack
620 int posix_memalign(void **out
, size_t al
, size_t size
) {
621 *out
= memalign(al
, size
);
626 #endif // THREAD_WRAPPERS_PTHREAD_H
627 // vim:shiftwidth=2:softtabstop=2:expandtab:foldmethod=marker