cpp-pthread  (v1.7.3)
Simple C++ wrapper to pthread functions.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Modules Pages
condition_variable.cpp
1 #include "pthread/condition_variable.hpp"
2 
3 namespace pthread {
4 
6  pthread_cond_wait ( &_condition, &mtx._mutex);
7  }
8 
10  // wait(*(lck.mutex()));
11  wait(*(lck._mutex));
12  }
13 
15  // return wait_for(*(lck.mutex()), millis);
16  return wait_for(*(lck._mutex), millis);
17  }
18 
19  /* Default millis is 0 */
21  int rc = 0;
22  cv_status status = no_timeout;
23 
24  if ( millis >= 0) {
25  milliseconds(millis);
26  }
27 
28  rc = pthread_cond_timedwait ( &_condition, &mtx._mutex, &timeout );
29 
30  switch (rc){
31 
32  case ETIMEDOUT:
33  status = timedout;
34  break;
35 
36  case EINVAL:
37  throw condition_variable_exception("The value specified by abstime is invalid.", rc);
38 
39  case EPERM:
40  throw condition_variable_exception("The mutex was not owned by the current thread at the time of the call.", rc);
41 
42  default:
43  status = no_timeout ;
44  break;
45  }
46 
47  return status;
48  }
49 
50 #if __cplusplus < 201103L
51  void condition_variable::notify_one() throw() {
52 #else
54 #endif
55  pthread_cond_signal ( &_condition );
56  }
57 
58 #if __cplusplus < 201103L
59  void condition_variable::notify_all () throw(){
60 #else
62 #endif
63  pthread_cond_broadcast ( &_condition );
64 
65  }
66 
67  void condition_variable::milliseconds(int millis){
68  timeval now;
69 
70  if ( gettimeofday ( &now, NULL ) == 0){
71  timeout.tv_sec = now.tv_sec;
72  // iss-44 - cppcheck - timeout.tv_nsec= now.tv_usec * 1000 ;
73 
74  auto seconds = millis / 1000;
75  auto nanos = (now.tv_usec * 1000) + ((millis % 1000) * 1000000) ;
76  seconds += nanos / 1000000000 ; // check if now + millis id not overflowing.
77  nanos = nanos % 1000000000 ;
78 
79  timeout.tv_sec += seconds ;
80  timeout.tv_nsec = nanos;
81  } else {
82  throw condition_variable_exception("failed to get current time.");
83  }
84  }
85 
86  // constuctors & destructors --------------
87 
88  condition_variable::condition_variable () {
89  int rc = pthread_cond_init ( &_condition, NULL );
90  if ( rc != 0 ){
91  throw condition_variable_exception("pthread_cond_init failed.", rc);
92  }
93  }
94 
95  condition_variable::~condition_variable () {
96  int rc = pthread_cond_destroy(&_condition);
97  if (rc != 0){
98  throw pthread_exception("pthread condition variable destroy failed.", rc);
99  }
100  }
101 
102 } // namespace pthread
cv_status wait_for(mutex &mtx, int millis)
pthread_mutex_t _mutex
Definition: mutex.hpp:74