ONPOSIX  2.0
 All Classes Namespaces Files Functions Variables Enumerator Friends Macros Pages
PosixCondition.hpp
Go to the documentation of this file.
1 /*
2  * PosixCondition.hpp
3  *
4  * Copyright (C) 2012 Evidence Srl - www.evidence.eu.com
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #ifndef POSIXCONDITION_HPP_
22 #define POSIXCONDITION_HPP_
23 
24 #include "PosixMutex.hpp"
25 #include "Time.hpp"
26 
27 
28 #include <pthread.h>
29 #include <time.h>
30 
31 namespace onposix {
32 
33 /**
34  * \brief Implementation of a condition variable.
35  *
36  * The class is non copyable and makes use of the pthread library.
37  */
39 
40  PosixCondition(const PosixMutex&);
42 
43  pthread_cond_t cond_;
44 
45 public:
48 
49  /**
50  * \brief Blocks the calling thread on the condition variable.
51  *
52  * These functions atomically release mutex and cause the calling thread
53  * to block on the condition variable.
54  * @param m Mutex released when blocking and acquired when unblocking.
55  * @return 0 in case of success
56  */
57  int wait(PosixMutex* m) {
58  return pthread_cond_wait(&cond_, &(m->mutex_));
59  }
60 
61  /**
62  * \brief Blocks the calling thread on the condition variable.
63  *
64  * These functions atomically release mutex and cause the calling thread
65  * to block on the condition variable.
66  * @param m Mutex released when blocking and acquired when unblocking.
67  * @param abstime Absolute time for timeout
68  * @return 0 in case of success, ETIMEDOUT in case of timeout
69  */
70  int timedWait(PosixMutex* m, const Time& abstime) {
71  timespec ts;
72  ts.tv_sec = abstime.getSeconds();
73  ts.tv_nsec = abstime.getNSeconds();
74  return pthread_cond_timedwait(&cond_, &(m->mutex_), &ts);
75  }
76 
77  /**
78  * \brief Unblocks at least one of the blocked threads.
79  *
80  * @return 0 in case of success
81  */
82  int signal() {
83  return pthread_cond_signal(&cond_);
84  }
85 
86  /**
87  * \brief Unblocks all blocked threads.
88  *
89  * @return 0 in case of success
90  */
91  int signalAll() {
92  return pthread_cond_broadcast(&cond_);
93  }
94 };
95 
96 
97 
98 } /* onposix */
99 
100 #endif /* POSIXCONDITION_HPP_ */