condition_variable 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. Copyright 2005-2013 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks.
  4. Threading Building Blocks is free software; you can redistribute it
  5. and/or modify it under the terms of the GNU General Public License
  6. version 2 as published by the Free Software Foundation.
  7. Threading Building Blocks is distributed in the hope that it will be
  8. useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  9. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with Threading Building Blocks; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. As a special exception, you may use this file as part of a free software
  15. library without restriction. Specifically, if other files instantiate
  16. templates or use macros or inline functions from this file, or you compile
  17. this file and link it with other files to produce an executable, this
  18. file does not by itself cause the resulting executable to be covered by
  19. the GNU General Public License. This exception does not however
  20. invalidate any other reasons why the executable file might be covered by
  21. the GNU General Public License.
  22. */
  23. #ifndef __TBB_condition_variable_H
  24. #define __TBB_condition_variable_H
  25. #if _WIN32||_WIN64
  26. #include "../machine/windows_api.h"
  27. namespace tbb {
  28. namespace interface5 {
  29. namespace internal {
  30. struct condition_variable_using_event
  31. {
  32. //! Event for blocking waiting threads.
  33. HANDLE event;
  34. //! Protects invariants involving n_waiters, release_count, and epoch.
  35. CRITICAL_SECTION mutex;
  36. //! Number of threads waiting on this condition variable
  37. int n_waiters;
  38. //! Number of threads remaining that should no longer wait on this condition variable.
  39. int release_count;
  40. //! To keep threads from waking up prematurely with earlier signals.
  41. unsigned epoch;
  42. };
  43. }}} // namespace tbb::interface5::internal
  44. #ifndef CONDITION_VARIABLE_INIT
  45. typedef void* CONDITION_VARIABLE;
  46. typedef CONDITION_VARIABLE* PCONDITION_VARIABLE;
  47. #endif
  48. #else /* if not _WIN32||_WIN64 */
  49. #include <errno.h> // some systems need it for ETIMEDOUT
  50. #include <pthread.h>
  51. #if __linux__
  52. #include <ctime>
  53. #else /* generic Unix */
  54. #include <sys/time.h>
  55. #endif
  56. #endif /* _WIN32||_WIN64 */
  57. #include "../tbb_stddef.h"
  58. #include "../mutex.h"
  59. #include "../tbb_thread.h"
  60. #include "../tbb_exception.h"
  61. #include "../tbb_profiling.h"
  62. namespace tbb {
  63. namespace interface5 {
  64. // C++0x standard working draft 30.4.3
  65. // Lock tag types
  66. struct defer_lock_t { }; //! do not acquire ownership of the mutex
  67. struct try_to_lock_t { }; //! try to acquire ownership of the mutex without blocking
  68. struct adopt_lock_t { }; //! assume the calling thread has already
  69. const defer_lock_t defer_lock = {};
  70. const try_to_lock_t try_to_lock = {};
  71. const adopt_lock_t adopt_lock = {};
  72. // C++0x standard working draft 30.4.3.1
  73. //! lock_guard
  74. template<typename M>
  75. class lock_guard : tbb::internal::no_copy {
  76. public:
  77. //! mutex type
  78. typedef M mutex_type;
  79. //! Constructor
  80. /** precondition: If mutex_type is not a recursive mutex, the calling thread
  81. does not own the mutex m. */
  82. explicit lock_guard(mutex_type& m) : pm(m) {m.lock();}
  83. //! Adopt_lock constructor
  84. /** precondition: the calling thread owns the mutex m. */
  85. lock_guard(mutex_type& m, adopt_lock_t) : pm(m) {}
  86. //! Destructor
  87. ~lock_guard() { pm.unlock(); }
  88. private:
  89. mutex_type& pm;
  90. };
  91. // C++0x standard working draft 30.4.3.2
  92. //! unique_lock
  93. template<typename M>
  94. class unique_lock : tbb::internal::no_copy {
  95. friend class condition_variable;
  96. public:
  97. typedef M mutex_type;
  98. // 30.4.3.2.1 construct/copy/destroy
  99. // NB: Without constructors that take an r-value reference to a unique_lock, the following constructor is of little use.
  100. //! Constructor
  101. /** postcondition: pm==0 && owns==false */
  102. unique_lock() : pm(NULL), owns(false) {}
  103. //! Constructor
  104. /** precondition: if mutex_type is not a recursive mutex, the calling thread
  105. does not own the mutex m. If the precondition is not met, a deadlock occurs.
  106. postcondition: pm==&m and owns==true */
  107. explicit unique_lock(mutex_type& m) : pm(&m) {m.lock(); owns=true;}
  108. //! Defer_lock constructor
  109. /** postcondition: pm==&m and owns==false */
  110. unique_lock(mutex_type& m, defer_lock_t) : pm(&m), owns(false) {}
  111. //! Try_to_lock constructor
  112. /** precondition: if mutex_type is not a recursive mutex, the calling thread
  113. does not own the mutex m. If the precondition is not met, a deadlock occurs.
  114. postcondition: pm==&m and owns==res where res is the value returned by
  115. the call to m.try_lock(). */
  116. unique_lock(mutex_type& m, try_to_lock_t) : pm(&m) {owns = m.try_lock();}
  117. //! Adopt_lock constructor
  118. /** precondition: the calling thread owns the mutex. If it does not, mutex->unlock() would fail.
  119. postcondition: pm==&m and owns==true */
  120. unique_lock(mutex_type& m, adopt_lock_t) : pm(&m), owns(true) {}
  121. //! Timed unique_lock acquisition.
  122. /** To avoid requiring support for namespace chrono, this method deviates from the working draft in that
  123. it uses tbb::tick_count::interval_t to specify the time duration. */
  124. unique_lock(mutex_type& m, const tick_count::interval_t &i) : pm(&m) {owns = try_lock_for( i );}
  125. //! Destructor
  126. ~unique_lock() { if( owns ) pm->unlock(); }
  127. // 30.4.3.2.2 locking
  128. //! Lock the mutex and own it.
  129. void lock() {
  130. if( pm ) {
  131. if( !owns ) {
  132. pm->lock();
  133. owns = true;
  134. } else
  135. throw_exception_v4( tbb::internal::eid_possible_deadlock );
  136. } else
  137. throw_exception_v4( tbb::internal::eid_operation_not_permitted );
  138. __TBB_ASSERT( owns, NULL );
  139. }
  140. //! Try to lock the mutex.
  141. /** If successful, note that this lock owns it. Otherwise, set it false. */
  142. bool try_lock() {
  143. if( pm ) {
  144. if( !owns )
  145. owns = pm->try_lock();
  146. else
  147. throw_exception_v4( tbb::internal::eid_possible_deadlock );
  148. } else
  149. throw_exception_v4( tbb::internal::eid_operation_not_permitted );
  150. return owns;
  151. }
  152. //! Try to lock the mutex.
  153. bool try_lock_for( const tick_count::interval_t &i );
  154. //! Unlock the mutex
  155. /** And note that this lock no longer owns it. */
  156. void unlock() {
  157. if( owns ) {
  158. pm->unlock();
  159. owns = false;
  160. } else
  161. throw_exception_v4( tbb::internal::eid_operation_not_permitted );
  162. __TBB_ASSERT( !owns, NULL );
  163. }
  164. // 30.4.3.2.3 modifiers
  165. //! Swap the two unique locks
  166. void swap(unique_lock& u) {
  167. mutex_type* t_pm = u.pm; u.pm = pm; pm = t_pm;
  168. bool t_owns = u.owns; u.owns = owns; owns = t_owns;
  169. }
  170. //! Release control over the mutex.
  171. mutex_type* release() {
  172. mutex_type* o_pm = pm;
  173. pm = NULL;
  174. owns = false;
  175. return o_pm;
  176. }
  177. // 30.4.3.2.4 observers
  178. //! Does this lock own the mutex?
  179. bool owns_lock() const { return owns; }
  180. // TODO: Un-comment 'explicit' when the last non-C++0x compiler support is dropped
  181. //! Does this lock own the mutex?
  182. /*explicit*/ operator bool() const { return owns; }
  183. //! Return the mutex that this lock currently has.
  184. mutex_type* mutex() const { return pm; }
  185. private:
  186. mutex_type* pm;
  187. bool owns;
  188. };
  189. template<typename M>
  190. bool unique_lock<M>::try_lock_for( const tick_count::interval_t &i)
  191. {
  192. const int unique_lock_tick = 100; /* microseconds; 0.1 milliseconds */
  193. // the smallest wait-time is 0.1 milliseconds.
  194. bool res = pm->try_lock();
  195. int duration_in_micro;
  196. if( !res && (duration_in_micro=int(i.seconds()*1e6))>unique_lock_tick ) {
  197. tick_count::interval_t i_100( double(unique_lock_tick)/1e6 /* seconds */); // 100 microseconds = 0.1*10E-3
  198. do {
  199. this_tbb_thread::sleep(i_100); // sleep for 100 micro seconds
  200. duration_in_micro -= unique_lock_tick;
  201. res = pm->try_lock();
  202. } while( !res && duration_in_micro>unique_lock_tick );
  203. }
  204. return (owns=res);
  205. }
  206. //! Swap the two unique locks that have the mutexes of same type
  207. template<typename M>
  208. void swap(unique_lock<M>& x, unique_lock<M>& y) { x.swap( y ); }
  209. namespace internal {
  210. #if _WIN32||_WIN64
  211. union condvar_impl_t {
  212. condition_variable_using_event cv_event;
  213. CONDITION_VARIABLE cv_native;
  214. };
  215. void __TBB_EXPORTED_FUNC internal_initialize_condition_variable( condvar_impl_t& cv );
  216. void __TBB_EXPORTED_FUNC internal_destroy_condition_variable( condvar_impl_t& cv );
  217. void __TBB_EXPORTED_FUNC internal_condition_variable_notify_one( condvar_impl_t& cv );
  218. void __TBB_EXPORTED_FUNC internal_condition_variable_notify_all( condvar_impl_t& cv );
  219. bool __TBB_EXPORTED_FUNC internal_condition_variable_wait( condvar_impl_t& cv, mutex* mtx, const tick_count::interval_t* i = NULL );
  220. #else /* if !(_WIN32||_WIN64), i.e., POSIX threads */
  221. typedef pthread_cond_t condvar_impl_t;
  222. #endif
  223. } // namespace internal
  224. //! cv_status
  225. /** C++0x standard working draft 30.5 */
  226. enum cv_status { no_timeout, timeout };
  227. //! condition variable
  228. /** C++0x standard working draft 30.5.1
  229. @ingroup synchronization */
  230. class condition_variable : tbb::internal::no_copy {
  231. public:
  232. //! Constructor
  233. condition_variable() {
  234. #if _WIN32||_WIN64
  235. internal_initialize_condition_variable( my_cv );
  236. #else
  237. pthread_cond_init( &my_cv, NULL );
  238. #endif
  239. }
  240. //! Destructor
  241. ~condition_variable() {
  242. //precondition: There shall be no thread blocked on *this.
  243. #if _WIN32||_WIN64
  244. internal_destroy_condition_variable( my_cv );
  245. #else
  246. pthread_cond_destroy( &my_cv );
  247. #endif
  248. }
  249. //! Notify one thread and wake it up
  250. void notify_one() {
  251. #if _WIN32||_WIN64
  252. internal_condition_variable_notify_one( my_cv );
  253. #else
  254. pthread_cond_signal( &my_cv );
  255. #endif
  256. }
  257. //! Notify all threads
  258. void notify_all() {
  259. #if _WIN32||_WIN64
  260. internal_condition_variable_notify_all( my_cv );
  261. #else
  262. pthread_cond_broadcast( &my_cv );
  263. #endif
  264. }
  265. //! Release the mutex associated with the lock and wait on this condition variable
  266. void wait(unique_lock<mutex>& lock);
  267. //! Wait on this condition variable while pred is false
  268. template <class Predicate>
  269. void wait(unique_lock<mutex>& lock, Predicate pred) {
  270. while( !pred() )
  271. wait( lock );
  272. }
  273. //! Timed version of wait()
  274. cv_status wait_for(unique_lock<mutex>& lock, const tick_count::interval_t &i );
  275. //! Timed version of the predicated wait
  276. /** The loop terminates when pred() returns true or when the time duration specified by rel_time (i) has elapsed. */
  277. template<typename Predicate>
  278. bool wait_for(unique_lock<mutex>& lock, const tick_count::interval_t &i, Predicate pred)
  279. {
  280. while( !pred() ) {
  281. cv_status st = wait_for( lock, i );
  282. if( st==timeout )
  283. return pred();
  284. }
  285. return true;
  286. }
  287. // C++0x standard working draft. 30.2.3
  288. typedef internal::condvar_impl_t* native_handle_type;
  289. native_handle_type native_handle() { return (native_handle_type) &my_cv; }
  290. private:
  291. internal::condvar_impl_t my_cv;
  292. };
  293. #if _WIN32||_WIN64
  294. inline void condition_variable::wait( unique_lock<mutex>& lock )
  295. {
  296. __TBB_ASSERT( lock.owns, NULL );
  297. lock.owns = false;
  298. if( !internal_condition_variable_wait( my_cv, lock.mutex() ) ) {
  299. int ec = GetLastError();
  300. // on Windows 7, SleepConditionVariableCS() may return ERROR_TIMEOUT while the doc says it returns WAIT_TIMEOUT
  301. __TBB_ASSERT_EX( ec!=WAIT_TIMEOUT&&ec!=ERROR_TIMEOUT, NULL );
  302. lock.owns = true;
  303. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  304. }
  305. lock.owns = true;
  306. }
  307. inline cv_status condition_variable::wait_for( unique_lock<mutex>& lock, const tick_count::interval_t& i )
  308. {
  309. cv_status rc = no_timeout;
  310. __TBB_ASSERT( lock.owns, NULL );
  311. lock.owns = false;
  312. // condvar_wait could be SleepConditionVariableCS (or SleepConditionVariableSRW) or our own pre-vista cond_var_wait()
  313. if( !internal_condition_variable_wait( my_cv, lock.mutex(), &i ) ) {
  314. int ec = GetLastError();
  315. if( ec==WAIT_TIMEOUT || ec==ERROR_TIMEOUT )
  316. rc = timeout;
  317. else {
  318. lock.owns = true;
  319. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  320. }
  321. }
  322. lock.owns = true;
  323. return rc;
  324. }
  325. #else /* !(_WIN32||_WIN64) */
  326. inline void condition_variable::wait( unique_lock<mutex>& lock )
  327. {
  328. __TBB_ASSERT( lock.owns, NULL );
  329. lock.owns = false;
  330. if( pthread_cond_wait( &my_cv, lock.mutex()->native_handle() ) ) {
  331. lock.owns = true;
  332. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  333. }
  334. // upon successful return, the mutex has been locked and is owned by the calling thread.
  335. lock.owns = true;
  336. }
  337. inline cv_status condition_variable::wait_for( unique_lock<mutex>& lock, const tick_count::interval_t& i )
  338. {
  339. #if __linux__
  340. struct timespec req;
  341. double sec = i.seconds();
  342. clock_gettime( CLOCK_REALTIME, &req );
  343. req.tv_sec += static_cast<long>(sec);
  344. req.tv_nsec += static_cast<long>( (sec - static_cast<long>(sec))*1e9 );
  345. #else /* generic Unix */
  346. struct timeval tv;
  347. struct timespec req;
  348. double sec = i.seconds();
  349. int status = gettimeofday(&tv, NULL);
  350. __TBB_ASSERT_EX( status==0, "gettimeofday failed" );
  351. req.tv_sec = tv.tv_sec + static_cast<long>(sec);
  352. req.tv_nsec = tv.tv_usec*1000 + static_cast<long>( (sec - static_cast<long>(sec))*1e9 );
  353. #endif /*(choice of OS) */
  354. if( req.tv_nsec>=1e9 ) {
  355. req.tv_sec += 1;
  356. req.tv_nsec -= static_cast<long int>(1e9);
  357. }
  358. __TBB_ASSERT( 0<=req.tv_nsec && req.tv_nsec<1e9, NULL );
  359. int ec;
  360. cv_status rc = no_timeout;
  361. __TBB_ASSERT( lock.owns, NULL );
  362. lock.owns = false;
  363. if( ( ec=pthread_cond_timedwait( &my_cv, lock.mutex()->native_handle(), &req ) ) ) {
  364. if( ec==ETIMEDOUT )
  365. rc = timeout;
  366. else {
  367. __TBB_ASSERT( lock.try_lock()==false, NULL );
  368. lock.owns = true;
  369. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  370. }
  371. }
  372. lock.owns = true;
  373. return rc;
  374. }
  375. #endif /* !(_WIN32||_WIN64) */
  376. } // namespace interface5
  377. __TBB_DEFINE_PROFILING_SET_NAME(interface5::condition_variable)
  378. } // namespace tbb
  379. #if TBB_IMPLEMENT_CPP0X
  380. namespace std {
  381. using tbb::interface5::defer_lock_t;
  382. using tbb::interface5::try_to_lock_t;
  383. using tbb::interface5::adopt_lock_t;
  384. using tbb::interface5::defer_lock;
  385. using tbb::interface5::try_to_lock;
  386. using tbb::interface5::adopt_lock;
  387. using tbb::interface5::lock_guard;
  388. using tbb::interface5::unique_lock;
  389. using tbb::interface5::swap; /* this is for void std::swap(unique_lock<M>&,unique_lock<M>&) */
  390. using tbb::interface5::condition_variable;
  391. using tbb::interface5::cv_status;
  392. using tbb::interface5::timeout;
  393. using tbb::interface5::no_timeout;
  394. } // namespace std
  395. #endif /* TBB_IMPLEMENT_CPP0X */
  396. #endif /* __TBB_condition_variable_H */