-
Notifications
You must be signed in to change notification settings - Fork 2
/
notification.c
61 lines (51 loc) · 1.54 KB
/
notification.c
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
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include "notification.h"
struct notification_desc {
pthread_mutex_t mutex;
pthread_cond_t cond;
};
int init_notification(struct notification *notification)
{
notification->desc = malloc(sizeof(struct notification_desc));
if (!notification->desc) {
printf("Unable to allocate notification descriptor\n");
return -1;
}
if (pthread_mutex_init(¬ification->desc->mutex, NULL) != 0) {
printf("Unable to init notification lock\n");
free(notification->desc);
return -1;
}
if (pthread_cond_init(¬ification->desc->cond, NULL) != 0) {
printf("Unable to init notification notificator\n");
free(notification->desc);
return -1;
}
return 0;
}
void destroy_notification(struct notification *notification)
{
pthread_mutex_destroy(¬ification->desc->mutex);
pthread_cond_destroy(¬ification->desc->cond);
free(notification->desc);
}
void wait_for_notification(struct notification *notification)
{
pthread_mutex_lock(¬ification->desc->mutex);
if (pthread_cond_wait(¬ification->desc->cond, ¬ification->desc->mutex) != 0) {
printf("Failed to wait for event\n");
return;
}
pthread_mutex_unlock(¬ification->desc->mutex);
}
void notify(struct notification *notification)
{
pthread_cond_signal(¬ification->desc->cond);
}
void notify_all(struct notification *notification)
{
pthread_cond_broadcast(¬ification->desc->cond);
}