-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwq.c
More file actions
67 lines (52 loc) · 1.66 KB
/
wq.c
File metadata and controls
67 lines (52 loc) · 1.66 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
#include <stdio.h>
#include <stdlib.h>
#include "wq.h"
#include "utlist.h"
#include <pthread.h>
//pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
//pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
/* Initializes a work queue WQ. */
void wq_init(wq_t *wq) {
/* TODO: Make me thread-safe! */
//pthread_mutex_lock(&lock);
if(wq==NULL){
wq = malloc(sizeof(*wq));
wq->size = 0;
wq->head = NULL;
pthread_mutex_init(&(wq->lock), 0);
pthread_cond_init(&(wq->cv),0);
}
//pthread_mutex_unlock(&lock);
}
/* 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) {
/* TODO: Make me blocking and thread-safe! */
pthread_mutex_lock(&(wq->lock));
while((wq->size)<=0){
pthread_cond_wait(&(wq->cv), &(wq->lock));
}
//critical section
wq_item_t *wq_item = wq->head;
int client_socket_fd = wq->head->client_socket_fd;
wq->size--;
DL_DELETE(wq->head, wq->head);
free(wq_item);
printf("%ld pop %d\n", pthread_self(), client_socket_fd);
pthread_mutex_unlock(&(wq->lock));
return client_socket_fd;
}
/* Add ITEM to WQ. */
void wq_push(wq_t *wq, int client_socket_fd) {
/* TODO: Make me thread-safe! */
pthread_mutex_lock(&(wq->lock));
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++;
//
printf("%ld push %d\n", pthread_self(),client_socket_fd);
//pthread_cond_signal(&cv);
pthread_cond_broadcast(&(wq->cv));
pthread_mutex_unlock(&(wq->lock));
}