Commit patch to not break on spaces.
[bowtie.git] / threading.h
1 #ifndef THREADING_H_
2 #define THREADING_H_
3
4 #include <iostream>
5 #include "spinlock.h"
6
7 // Note that USE_SPINLOCK trumps BOWTIE_PTHREADS
8
9 #ifdef BOWTIE_PTHREADS
10 #include <pthread.h>
11 #endif
12
13 #ifdef USE_SPINLOCK
14 #  include "spinlock.h"
15 #  define MUTEX_T SpinLock
16 #  define MUTEX_INIT(l)
17 #  define MUTEX_LOCK(l) (l).Enter()
18 #  define MUTEX_UNLOCK(l) (l).Leave()
19 #else
20 #  ifdef BOWTIE_PTHREADS
21 #    define MUTEX_T pthread_mutex_t
22 #    define MUTEX_INIT(l) pthread_mutex_init(&l, NULL)
23 #    define MUTEX_LOCK(l) pthread_mutex_lock(&l)
24 #    define MUTEX_UNLOCK(l) pthread_mutex_unlock(&l)
25 #  else
26 #    define MUTEX_T int
27 #    define MUTEX_INIT(l) l = 0
28 #    define MUTEX_LOCK(l) l = 1
29 #    define MUTEX_UNLOCK(l) l = 0
30 #  endif /* BOWTIE_PTHREADS */
31 #endif /* USE_SPINLOCK */
32
33 #ifdef BOWTIE_PTHREADS
34 static inline void joinThread(pthread_t th) {
35         int ret, *tmp;
36         if((ret = pthread_join(th, (void**)(int**)&tmp)) != 0) {
37                 std::cerr << "Error: pthread_join returned non-zero status: "
38                           << ret << std::endl;
39                 throw 1;
40         }
41 }
42
43 static inline void createThread(pthread_t* th,
44                                 void *(*start_routine) (void *),
45                                 void *arg)
46 {
47         int ret;
48         pthread_attr_t pt_attr;
49         pthread_attr_init(&pt_attr);
50         pthread_attr_setdetachstate(&pt_attr, PTHREAD_CREATE_JOINABLE);
51         pthread_attr_setstacksize(&pt_attr, 2 << 20);
52         if((ret = pthread_create(th, &pt_attr, start_routine, arg)) != 0) {
53                 std::cerr << "Error: pthread_create returned non-zero status: "
54                           << ret << std::endl;
55                 throw 1;
56         }
57 }
58 #endif
59
60 /**
61  * Wrap a lock; obtain lock upon construction, release upon destruction.
62  */
63 class ThreadSafe {
64 public:
65         ThreadSafe(MUTEX_T* lock) {
66                 lock_ = lock;
67                 MUTEX_LOCK(*lock_);
68         }
69         ~ThreadSafe() { MUTEX_UNLOCK(*lock_); }
70 private:
71         MUTEX_T *lock_;
72 };
73
74 #endif