-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread-event.h
72 lines (64 loc) · 1.3 KB
/
thread-event.h
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
#ifndef __THREAD_EVENT_H__
#define __THREAD_EVENT_H__
#ifdef _WIN32
typedef HANDLE thread_event;
#else
#include <pthread.h>
typedef struct thread_event {
int set;
pthread_mutex_t mutex;
pthread_cond_t cond;
} thread_event;
#endif
static inline
int thread_event_init(thread_event *ev)
{
#ifdef _WIN32
if (!(*ev = CreateEvent(NULL, FALSE, FALSE, NULL))) {
Werr(1, "%s: CreateEvent failed", __FUNCTION__);
return -1;
}
#else
ev->set = 0;
pthread_mutex_init(&ev->mutex, NULL);
pthread_cond_init(&ev->cond, NULL);
#endif
return 0;
}
static inline
void thread_event_set(thread_event *ev)
{
#ifdef _WIN32
SetEvent(*ev);
#else
pthread_mutex_lock(&ev->mutex);
ev->set = 1;
pthread_cond_signal(&ev->cond);
pthread_mutex_unlock(&ev->mutex);
#endif
}
static inline
void thread_event_wait(thread_event *ev)
{
#ifdef _WIN32
WaitForSingleObject(*ev, INFINITE);
#else
pthread_mutex_lock(&ev->mutex);
while (!ev->set) {
pthread_cond_wait(&ev->cond, &ev->mutex);
}
ev->set = 0;
pthread_mutex_unlock(&ev->mutex);
#endif
}
static inline
void thread_event_close(thread_event *ev)
{
#ifdef _WIN32
CloseHandle(*ev);
#else
pthread_cond_destroy(&ev->cond);
pthread_mutex_destroy(&ev->mutex);
#endif
}
#endif /* __THREAD_EVENT_H__ */