ThreadingUtil.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef THREADINGUTIL_H_
  19. #define THREADINGUTIL_H_
  20. #include <vector>
  21. #ifdef THREADED
  22. #include "pthread.h"
  23. #endif
  24. // *****************************************************************************
  25. // Threading primitives
  26. // atomic post-increment; returns the previous value of the operand
  27. int32_t atomic_post_incr(volatile int32_t* operand, int32_t incr);
  28. // atomic fetch&store; returns the previous value of the operand
  29. int32_t atomic_fetch_store(volatile int32_t *operand, int32_t value);
  30. // a partial implementation of an atomic integer type
  31. class AtomicInt{
  32. public:
  33. explicit AtomicInt(int32_t init=0):v_(init){}
  34. AtomicInt(const AtomicInt& other):v_(other){}
  35. // assignment
  36. AtomicInt& operator=(const AtomicInt& lhs){
  37. atomic_fetch_store(&v_,lhs);
  38. return *this;
  39. }
  40. AtomicInt& operator=(int32_t i){
  41. atomic_fetch_store(&v_,i);
  42. return *this;
  43. }
  44. // pre-increment
  45. AtomicInt& operator++() {
  46. atomic_post_incr(&v_,1);
  47. return *this;
  48. }
  49. // pre-decrement
  50. AtomicInt& operator--() {
  51. atomic_post_incr(&v_,-1);
  52. return *this;
  53. }
  54. // post-increment
  55. AtomicInt operator++(int){
  56. return AtomicInt(atomic_post_incr(&v_,1));
  57. }
  58. // post-decrement
  59. AtomicInt operator--(int){
  60. return AtomicInt(atomic_post_incr(&v_,-1));
  61. }
  62. operator int() const{
  63. return atomic_post_incr(&v_,0);
  64. }
  65. int get() const{
  66. return atomic_post_incr(&v_,0);
  67. }
  68. private:
  69. mutable int32_t v_;
  70. };
  71. #ifdef THREADED
  72. // ****************************************************************************
  73. #define VALIDATE_JOBS(jm) jm.validateJobs(__FILE__,__LINE__)
  74. #define VALIDATE_JOB(j) j.validate(__FILE__,__LINE__)
  75. class Mutex{
  76. public:
  77. Mutex();
  78. ~Mutex();
  79. void acquire();
  80. void release();
  81. private:
  82. Mutex(const Mutex&);
  83. Mutex& operator=(const Mutex&);
  84. struct Impl;
  85. Impl* impl_;
  86. };
  87. class MTLock{
  88. public:
  89. MTLock(Mutex& m):m_(m){m.acquire();}
  90. ~MTLock(){m_.release();}
  91. Mutex& m_;
  92. };
  93. #define synchronized(m) MTLock __lock(m)
  94. // ****************************************************************************
  95. class Latch {
  96. public:
  97. virtual ~Latch() {}
  98. virtual void await() const =0;
  99. virtual void signalAndWait() =0;
  100. virtual void signal() =0;
  101. };
  102. class CountDownLatch: public Latch {
  103. public:
  104. CountDownLatch(int count):count_(count) {
  105. pthread_cond_init(&cond_,0);
  106. pthread_mutex_init(&mut_,0);
  107. }
  108. virtual ~CountDownLatch() {
  109. pthread_mutex_lock(&mut_);
  110. if(count_!=0) {
  111. count_=0;
  112. pthread_cond_broadcast(&cond_);
  113. }
  114. pthread_mutex_unlock(&mut_);
  115. pthread_cond_destroy(&cond_);
  116. pthread_mutex_destroy(&mut_);
  117. }
  118. virtual void await() const {
  119. pthread_mutex_lock(&mut_);
  120. awaitImpl();
  121. pthread_mutex_unlock(&mut_);
  122. }
  123. virtual void signalAndWait() {
  124. pthread_mutex_lock(&mut_);
  125. signalImpl();
  126. awaitImpl();
  127. pthread_mutex_unlock(&mut_);
  128. }
  129. virtual void signal() {
  130. pthread_mutex_lock(&mut_);
  131. signalImpl();
  132. pthread_mutex_unlock(&mut_);
  133. }
  134. private:
  135. void awaitImpl() const{
  136. while(count_!=0)
  137. pthread_cond_wait(&cond_,&mut_);
  138. }
  139. void signalImpl() {
  140. if(count_>0) {
  141. count_--;
  142. pthread_cond_broadcast(&cond_);
  143. }
  144. }
  145. int count_;
  146. mutable pthread_mutex_t mut_;
  147. mutable pthread_cond_t cond_;
  148. };
  149. class TestJob {
  150. public:
  151. typedef long JobId;
  152. TestJob():hasRun_(false),startLatch_(0),endLatch_(0) {}
  153. virtual ~TestJob() {
  154. join();
  155. }
  156. virtual TestJob* clone() const =0;
  157. virtual void run() =0;
  158. virtual void validate(const char* file, int line) const =0;
  159. virtual void start(Latch* startLatch=0,Latch* endLatch=0) {
  160. startLatch_=startLatch;endLatch_=endLatch;
  161. hasRun_=true;
  162. pthread_create(&thread_, 0, thread, this);
  163. }
  164. virtual JobId getJobId() const {
  165. return (JobId)thread_;
  166. }
  167. virtual void join() {
  168. if(!hasRun_)
  169. return;
  170. if(!pthread_equal(thread_,pthread_self()))
  171. pthread_join(thread_,0);
  172. else
  173. pthread_detach(thread_);
  174. }
  175. private:
  176. void awaitStart() {
  177. if(startLatch_==0) return;
  178. startLatch_->signalAndWait();
  179. }
  180. void signalFinished() {
  181. if(endLatch_==0) return;
  182. endLatch_->signal();
  183. }
  184. static void* thread(void* p) {
  185. TestJob* j=(TestJob*)p;
  186. j->awaitStart(); // wait for the start command
  187. j->run();
  188. j->signalFinished();
  189. return 0;
  190. }
  191. bool hasRun_;
  192. Latch* startLatch_;
  193. Latch* endLatch_;
  194. pthread_t thread_;
  195. };
  196. class TestJobManager {
  197. typedef std::vector<TestJob*> JobList;
  198. public:
  199. TestJobManager(const TestJob& tj,int threadCount=1):
  200. startLatch_(threadCount),endLatch_(threadCount)
  201. {
  202. for(int i=0;i<threadCount;++i)
  203. jobs_.push_back(tj.clone());
  204. }
  205. virtual ~TestJobManager(){
  206. for(unsigned i=0;i<jobs_.size();++i)
  207. delete jobs_[i];
  208. }
  209. virtual void startAllJobs() {
  210. for(unsigned i=0;i<jobs_.size();++i)
  211. jobs_[i]->start(&startLatch_,&endLatch_);
  212. }
  213. virtual void startJobsImmediately() {
  214. for(unsigned i=0;i<jobs_.size();++i)
  215. jobs_[i]->start(0,&endLatch_);
  216. }
  217. virtual void wait() const {
  218. endLatch_.await();
  219. }
  220. virtual void validateJobs(const char* file, int line) const{
  221. for(unsigned i=0;i<jobs_.size();++i)
  222. jobs_[i]->validate(file,line);
  223. }
  224. private:
  225. JobList jobs_;
  226. CountDownLatch startLatch_;
  227. CountDownLatch endLatch_;
  228. };
  229. #else // THREADED
  230. // single THREADED
  231. class Mutex{
  232. public:
  233. void acquire(){}
  234. void release(){}
  235. };
  236. #define synchronized(m)
  237. #endif // THREADED
  238. #endif /*THREADINGUTIL_H_*/