summaryrefslogtreecommitdiff
path: root/tvapi/libtv/tvutils/CCondition.h (plain)
blob: 4313f71db65f98ae61951b9862cdee56eeadc15b
1/*
2reference android api, just linux pthread
3*/
4
5#ifndef _TV_UTILS_CONDITION_H
6#define _TV_UTILS_CONDITION_H
7
8#include <stdint.h>
9#include <sys/types.h>
10#include <time.h>
11#include <pthread.h>
12#include "CMutex.h"
13
14typedef long long nsecs_t;
15
16class CCondition
17{
18public:
19 enum {
20 PRIVATE = 0,
21 SHARED = 1
22 };
23
24 CCondition();
25 CCondition(int type);
26 ~CCondition();
27 // Wait on the condition variable. Lock the mutex before calling.
28 int wait(CMutex &mutex);
29 // same with relative timeout
30 int waitRelative(CMutex &mutex, long sec);
31 // Signal the condition variable, allowing one thread to continue.
32 void signal();
33 // Signal the condition variable, allowing all threads to continue.
34 void broadcast();
35
36private:
37 pthread_cond_t mCond;
38};
39
40
41
42// ---------------------------------------------------------------------------
43
44inline CCondition::CCondition()
45{
46 pthread_cond_init(&mCond, NULL);
47}
48inline CCondition::CCondition(int type)
49{
50 if (type == SHARED) {
51 pthread_condattr_t attr;
52 pthread_condattr_init(&attr);
53 pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
54 pthread_cond_init(&mCond, &attr);
55 pthread_condattr_destroy(&attr);
56 } else {
57 pthread_cond_init(&mCond, NULL);
58 }
59}
60inline CCondition::~CCondition()
61{
62 pthread_cond_destroy(&mCond);
63}
64inline int CCondition::wait(CMutex &mutex)
65{
66 return -pthread_cond_wait(&mCond, &mutex.mMutex);
67}
68inline int CCondition::waitRelative(CMutex &mutex, long msec)
69{
70 struct timespec ts;
71 long _nanoSec = 1000000000;
72 int _sec = msec / 1000;
73 long _nsec = (msec - 1000 * _sec) * 1000000;
74 clock_gettime(CLOCK_REALTIME, &ts);
75 ts.tv_sec += _sec;
76 ts.tv_nsec += _nsec;
77 if (ts.tv_nsec > _nanoSec) {
78 ts.tv_nsec %= _nanoSec;
79 ts.tv_sec++;
80 }
81 return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
82}
83inline void CCondition::signal()
84{
85 pthread_cond_signal(&mCond);
86}
87inline void CCondition::broadcast()
88{
89 pthread_cond_broadcast(&mCond);
90}
91#endif
92