forked from anqin/trident
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcondition_variable.h
More file actions
84 lines (74 loc) · 1.79 KB
/
condition_variable.h
File metadata and controls
84 lines (74 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright (c) 2014 The Trident Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
//
#ifndef _TRIDENT_CONDITION_VARIABLE_H_
#define _TRIDENT_CONDITION_VARIABLE_H_
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <trident/common.h>
#include <trident/mutex_lock.h>
namespace trident {
class ConditionVariable
{
public:
ConditionVariable()
{
pthread_cond_init(&_cond, NULL);
}
~ConditionVariable()
{
pthread_cond_destroy(&_cond);
}
void wait(MutexLock& mutex)
{
SCHECK_EQ(0, pthread_cond_wait(&_cond, &mutex._lock));
}
bool wait(MutexLock& mutex, int64 timeout_in_ms)
{
if (timeout_in_ms < 0)
{
wait(mutex);
return true;
}
timespec ts;
calculate_expiration(timeout_in_ms, &ts);
int error = pthread_cond_timedwait(&_cond, &mutex._lock, &ts);
if (error == 0)
{
return true;
}
else if (error == ETIMEDOUT)
{
return false;
}
else
{
SLOG(FATAL, "error no: %d", error);
}
}
void signal()
{
SCHECK_EQ(0, pthread_cond_signal(&_cond));
}
void broadcast()
{
SCHECK_EQ(0, pthread_cond_broadcast(&_cond));
}
private:
void calculate_expiration(int64 timeout_in_ms, timespec* ts)
{
timeval tv;
gettimeofday(&tv, NULL);
int64 usec = tv.tv_usec + timeout_in_ms * 1000LL;
ts->tv_sec = tv.tv_sec + usec / 1000000;
ts->tv_nsec = (usec % 1000000) * 1000;
}
private:
pthread_cond_t _cond;
};
} // namespace trident
#endif // _TRIDENT_CONDITION_VARIABLE_H_
/* vim: set ts=4 sw=4 sts=4 tw=100 */