condition_variable 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*
  2. Copyright (c) 2005-2020 Intel Corporation
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #include "../internal/_deprecated_header_message_guard.h"
  14. #if !defined(__TBB_show_deprecation_message_condition_variable_H) && defined(__TBB_show_deprecated_header_message)
  15. #define __TBB_show_deprecation_message_condition_variable_H
  16. #pragma message("TBB Warning: tbb/compat/condition_variable is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual.")
  17. #endif
  18. #if defined(__TBB_show_deprecated_header_message)
  19. #undef __TBB_show_deprecated_header_message
  20. #endif
  21. #ifndef __TBB_condition_variable_H
  22. #define __TBB_condition_variable_H
  23. #define __TBB_condition_variable_H_include_area
  24. #include "../internal/_warning_suppress_enable_notice.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 __TBB_DEPRECATED_IN_VERBOSE_MODE defer_lock_t { }; //! do not acquire ownership of the mutex
  67. struct __TBB_DEPRECATED_IN_VERBOSE_MODE try_to_lock_t { }; //! try to acquire ownership of the mutex without blocking
  68. struct __TBB_DEPRECATED_IN_VERBOSE_MODE adopt_lock_t { }; //! assume the calling thread has already
  69. __TBB_DEPRECATED_IN_VERBOSE_MODE const defer_lock_t defer_lock = {};
  70. __TBB_DEPRECATED_IN_VERBOSE_MODE const try_to_lock_t try_to_lock = {};
  71. __TBB_DEPRECATED_IN_VERBOSE_MODE 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 __TBB_DEPRECATED_IN_VERBOSE_MODE 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 __TBB_DEPRECATED_IN_VERBOSE_MODE 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. #if __TBB_CPP11_RVALUE_REF_PRESENT
  126. //! Move constructor
  127. /** postconditions: pm == src_p.pm and owns == src_p.owns (where src_p is the state of src just prior to this
  128. construction), src.pm == 0 and src.owns == false. */
  129. unique_lock(unique_lock && src): pm(NULL), owns(false) {this->swap(src);}
  130. //! Move assignment
  131. /** effects: If owns calls pm->unlock().
  132. Postconditions: pm == src_p.pm and owns == src_p.owns (where src_p is the state of src just prior to this
  133. assignment), src.pm == 0 and src.owns == false. */
  134. unique_lock& operator=(unique_lock && src) {
  135. if (owns)
  136. this->unlock();
  137. pm = NULL;
  138. this->swap(src);
  139. return *this;
  140. }
  141. #endif // __TBB_CPP11_RVALUE_REF_PRESENT
  142. //! Destructor
  143. ~unique_lock() { if( owns ) pm->unlock(); }
  144. // 30.4.3.2.2 locking
  145. //! Lock the mutex and own it.
  146. void lock() {
  147. if( pm ) {
  148. if( !owns ) {
  149. pm->lock();
  150. owns = true;
  151. } else
  152. throw_exception_v4( tbb::internal::eid_possible_deadlock );
  153. } else
  154. throw_exception_v4( tbb::internal::eid_operation_not_permitted );
  155. __TBB_ASSERT( owns, NULL );
  156. }
  157. //! Try to lock the mutex.
  158. /** If successful, note that this lock owns it. Otherwise, set it false. */
  159. bool try_lock() {
  160. if( pm ) {
  161. if( !owns )
  162. owns = pm->try_lock();
  163. else
  164. throw_exception_v4( tbb::internal::eid_possible_deadlock );
  165. } else
  166. throw_exception_v4( tbb::internal::eid_operation_not_permitted );
  167. return owns;
  168. }
  169. //! Try to lock the mutex.
  170. bool try_lock_for( const tick_count::interval_t &i );
  171. //! Unlock the mutex
  172. /** And note that this lock no longer owns it. */
  173. void unlock() {
  174. if( owns ) {
  175. pm->unlock();
  176. owns = false;
  177. } else
  178. throw_exception_v4( tbb::internal::eid_operation_not_permitted );
  179. __TBB_ASSERT( !owns, NULL );
  180. }
  181. // 30.4.3.2.3 modifiers
  182. //! Swap the two unique locks
  183. void swap(unique_lock& u) {
  184. mutex_type* t_pm = u.pm; u.pm = pm; pm = t_pm;
  185. bool t_owns = u.owns; u.owns = owns; owns = t_owns;
  186. }
  187. //! Release control over the mutex.
  188. mutex_type* release() {
  189. mutex_type* o_pm = pm;
  190. pm = NULL;
  191. owns = false;
  192. return o_pm;
  193. }
  194. // 30.4.3.2.4 observers
  195. //! Does this lock own the mutex?
  196. bool owns_lock() const { return owns; }
  197. // TODO: Un-comment 'explicit' when the last non-C++0x compiler support is dropped
  198. //! Does this lock own the mutex?
  199. /*explicit*/ operator bool() const { return owns; }
  200. //! Return the mutex that this lock currently has.
  201. mutex_type* mutex() const { return pm; }
  202. private:
  203. mutex_type* pm;
  204. bool owns;
  205. };
  206. template<typename M>
  207. __TBB_DEPRECATED_IN_VERBOSE_MODE bool unique_lock<M>::try_lock_for( const tick_count::interval_t &i)
  208. {
  209. const int unique_lock_tick = 100; /* microseconds; 0.1 milliseconds */
  210. // the smallest wait-time is 0.1 milliseconds.
  211. bool res = pm->try_lock();
  212. int duration_in_micro;
  213. if( !res && (duration_in_micro=int(i.seconds()*1e6))>unique_lock_tick ) {
  214. tick_count::interval_t i_100( double(unique_lock_tick)/1e6 /* seconds */); // 100 microseconds = 0.1*10E-3
  215. do {
  216. this_tbb_thread::sleep(i_100); // sleep for 100 micro seconds
  217. duration_in_micro -= unique_lock_tick;
  218. res = pm->try_lock();
  219. } while( !res && duration_in_micro>unique_lock_tick );
  220. }
  221. return (owns=res);
  222. }
  223. //! Swap the two unique locks that have the mutexes of same type
  224. template<typename M>
  225. void swap(unique_lock<M>& x, unique_lock<M>& y) { x.swap( y ); }
  226. namespace internal {
  227. #if _WIN32||_WIN64
  228. union condvar_impl_t {
  229. condition_variable_using_event cv_event;
  230. CONDITION_VARIABLE cv_native;
  231. };
  232. void __TBB_EXPORTED_FUNC internal_initialize_condition_variable( condvar_impl_t& cv );
  233. void __TBB_EXPORTED_FUNC internal_destroy_condition_variable( condvar_impl_t& cv );
  234. void __TBB_EXPORTED_FUNC internal_condition_variable_notify_one( condvar_impl_t& cv );
  235. void __TBB_EXPORTED_FUNC internal_condition_variable_notify_all( condvar_impl_t& cv );
  236. bool __TBB_EXPORTED_FUNC internal_condition_variable_wait( condvar_impl_t& cv, mutex* mtx, const tick_count::interval_t* i = NULL );
  237. #else /* if !(_WIN32||_WIN64), i.e., POSIX threads */
  238. typedef pthread_cond_t condvar_impl_t;
  239. #endif
  240. } // namespace internal
  241. //! cv_status
  242. /** C++0x standard working draft 30.5 */
  243. enum cv_status { no_timeout, timeout };
  244. //! condition variable
  245. /** C++0x standard working draft 30.5.1
  246. @ingroup synchronization */
  247. class __TBB_DEPRECATED_IN_VERBOSE_MODE condition_variable : tbb::internal::no_copy {
  248. public:
  249. //! Constructor
  250. condition_variable() {
  251. #if _WIN32||_WIN64
  252. internal_initialize_condition_variable( my_cv );
  253. #else
  254. pthread_cond_init( &my_cv, NULL );
  255. #endif
  256. }
  257. //! Destructor
  258. ~condition_variable() {
  259. //precondition: There shall be no thread blocked on *this.
  260. #if _WIN32||_WIN64
  261. internal_destroy_condition_variable( my_cv );
  262. #else
  263. pthread_cond_destroy( &my_cv );
  264. #endif
  265. }
  266. //! Notify one thread and wake it up
  267. void notify_one() {
  268. #if _WIN32||_WIN64
  269. internal_condition_variable_notify_one( my_cv );
  270. #else
  271. pthread_cond_signal( &my_cv );
  272. #endif
  273. }
  274. //! Notify all threads
  275. void notify_all() {
  276. #if _WIN32||_WIN64
  277. internal_condition_variable_notify_all( my_cv );
  278. #else
  279. pthread_cond_broadcast( &my_cv );
  280. #endif
  281. }
  282. //! Release the mutex associated with the lock and wait on this condition variable
  283. void wait(unique_lock<mutex>& lock);
  284. //! Wait on this condition variable while pred is false
  285. template <class Predicate>
  286. void wait(unique_lock<mutex>& lock, Predicate pred) {
  287. while( !pred() )
  288. wait( lock );
  289. }
  290. //! Timed version of wait()
  291. cv_status wait_for(unique_lock<mutex>& lock, const tick_count::interval_t &i );
  292. //! Timed version of the predicated wait
  293. /** The loop terminates when pred() returns true or when the time duration specified by rel_time (i) has elapsed. */
  294. template<typename Predicate>
  295. bool wait_for(unique_lock<mutex>& lock, const tick_count::interval_t &i, Predicate pred)
  296. {
  297. while( !pred() ) {
  298. cv_status st = wait_for( lock, i );
  299. if( st==timeout )
  300. return pred();
  301. }
  302. return true;
  303. }
  304. // C++0x standard working draft. 30.2.3
  305. typedef internal::condvar_impl_t* native_handle_type;
  306. native_handle_type native_handle() { return (native_handle_type) &my_cv; }
  307. private:
  308. internal::condvar_impl_t my_cv;
  309. };
  310. #if _WIN32||_WIN64
  311. inline void condition_variable::wait( unique_lock<mutex>& lock )
  312. {
  313. __TBB_ASSERT( lock.owns, NULL );
  314. lock.owns = false;
  315. if( !internal_condition_variable_wait( my_cv, lock.mutex() ) ) {
  316. int ec = GetLastError();
  317. // on Windows 7, SleepConditionVariableCS() may return ERROR_TIMEOUT while the doc says it returns WAIT_TIMEOUT
  318. __TBB_ASSERT_EX( ec!=WAIT_TIMEOUT&&ec!=ERROR_TIMEOUT, NULL );
  319. lock.owns = true;
  320. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  321. }
  322. lock.owns = true;
  323. }
  324. inline cv_status condition_variable::wait_for( unique_lock<mutex>& lock, const tick_count::interval_t& i )
  325. {
  326. cv_status rc = no_timeout;
  327. __TBB_ASSERT( lock.owns, NULL );
  328. lock.owns = false;
  329. // condvar_wait could be SleepConditionVariableCS (or SleepConditionVariableSRW) or our own pre-vista cond_var_wait()
  330. if( !internal_condition_variable_wait( my_cv, lock.mutex(), &i ) ) {
  331. int ec = GetLastError();
  332. if( ec==WAIT_TIMEOUT || ec==ERROR_TIMEOUT )
  333. rc = timeout;
  334. else {
  335. lock.owns = true;
  336. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  337. }
  338. }
  339. lock.owns = true;
  340. return rc;
  341. }
  342. #else /* !(_WIN32||_WIN64) */
  343. inline void condition_variable::wait( unique_lock<mutex>& lock )
  344. {
  345. __TBB_ASSERT( lock.owns, NULL );
  346. lock.owns = false;
  347. if( pthread_cond_wait( &my_cv, lock.mutex()->native_handle() ) ) {
  348. lock.owns = true;
  349. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  350. }
  351. // upon successful return, the mutex has been locked and is owned by the calling thread.
  352. lock.owns = true;
  353. }
  354. inline cv_status condition_variable::wait_for( unique_lock<mutex>& lock, const tick_count::interval_t& i )
  355. {
  356. #if __linux__
  357. struct timespec req;
  358. double sec = i.seconds();
  359. clock_gettime( CLOCK_REALTIME, &req );
  360. req.tv_sec += static_cast<long>(sec);
  361. req.tv_nsec += static_cast<long>( (sec - static_cast<long>(sec))*1e9 );
  362. #else /* generic Unix */
  363. struct timeval tv;
  364. struct timespec req;
  365. double sec = i.seconds();
  366. int status = gettimeofday(&tv, NULL);
  367. __TBB_ASSERT_EX( status==0, "gettimeofday failed" );
  368. req.tv_sec = tv.tv_sec + static_cast<long>(sec);
  369. req.tv_nsec = tv.tv_usec*1000 + static_cast<long>( (sec - static_cast<long>(sec))*1e9 );
  370. #endif /*(choice of OS) */
  371. if( req.tv_nsec>=1e9 ) {
  372. req.tv_sec += 1;
  373. req.tv_nsec -= static_cast<long int>(1e9);
  374. }
  375. __TBB_ASSERT( 0<=req.tv_nsec && req.tv_nsec<1e9, NULL );
  376. int ec;
  377. cv_status rc = no_timeout;
  378. __TBB_ASSERT( lock.owns, NULL );
  379. lock.owns = false;
  380. if( ( ec=pthread_cond_timedwait( &my_cv, lock.mutex()->native_handle(), &req ) ) ) {
  381. if( ec==ETIMEDOUT )
  382. rc = timeout;
  383. else {
  384. __TBB_ASSERT( lock.try_lock()==false, NULL );
  385. lock.owns = true;
  386. throw_exception_v4( tbb::internal::eid_condvar_wait_failed );
  387. }
  388. }
  389. lock.owns = true;
  390. return rc;
  391. }
  392. #endif /* !(_WIN32||_WIN64) */
  393. } // namespace interface5
  394. __TBB_DEFINE_PROFILING_SET_NAME(interface5::condition_variable)
  395. } // namespace tbb
  396. #if TBB_IMPLEMENT_CPP0X
  397. namespace std {
  398. using tbb::interface5::defer_lock_t;
  399. using tbb::interface5::try_to_lock_t;
  400. using tbb::interface5::adopt_lock_t;
  401. using tbb::interface5::defer_lock;
  402. using tbb::interface5::try_to_lock;
  403. using tbb::interface5::adopt_lock;
  404. using tbb::interface5::lock_guard;
  405. using tbb::interface5::unique_lock;
  406. using tbb::interface5::swap; /* this is for void std::swap(unique_lock<M>&,unique_lock<M>&) */
  407. using tbb::interface5::condition_variable;
  408. using tbb::interface5::cv_status;
  409. using tbb::interface5::timeout;
  410. using tbb::interface5::no_timeout;
  411. } // namespace std
  412. #endif /* TBB_IMPLEMENT_CPP0X */
  413. #include "../internal/_warning_suppress_disable_notice.h"
  414. #undef __TBB_condition_variable_H_include_area
  415. #endif /* __TBB_condition_variable_H */