-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwq.c
More file actions
executable file
·38 lines (34 loc) · 1022 Bytes
/
wq.c
File metadata and controls
executable file
·38 lines (34 loc) · 1022 Bytes
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
#include <stdlib.h>
#include "wq.h"
#include "utlist.h"
/* Initializes a work queue WQ. */
void wq_init(wq_t *wq) {
pthread_mutex_init(&wq->mutex, NULL);
pthread_cond_init(&wq->condvar, NULL);
wq->size = 0;
wq->head = NULL;
}
/* Remove an item from the WQ. This function should block until there
* is at least one item on the queue. */
int wq_pop(wq_t *wq) {
pthread_mutex_lock(&wq->mutex);
while (wq->size == 0)
pthread_cond_wait(&wq->condvar, &wq->mutex);
wq_item_t *wq_item = wq->head;
int client_socket_fd = wq->head->client_socket_fd;
wq->size--;
DL_DELETE(wq->head, wq->head);
pthread_mutex_unlock(&wq->mutex);
free(wq_item);
return client_socket_fd;
}
/* Add ITEM to WQ. */
void wq_push(wq_t *wq, int client_socket_fd) {
pthread_mutex_lock(&wq->mutex);
wq_item_t *wq_item = calloc(1, sizeof(wq_item_t));
wq_item->client_socket_fd = client_socket_fd;
DL_APPEND(wq->head, wq_item);
wq->size++;
pthread_cond_broadcast(&wq->condvar);
pthread_mutex_unlock(&wq->mutex);
}