Created
December 28, 2014 20:04
-
-
Save cpq/3502fab49ccdb73320dc to your computer and use it in GitHub Desktop.
One-to-many producer/consumer implementation on top of POSIX API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct task { | |
| socket_t accepted_socket; | |
| }; | |
| struct queue { | |
| struct task tasks[NUM_WORKER_THREADS]; | |
| int num_tasks; | |
| pthread_mutex_t mutex; | |
| pthread_cond_t condvar; | |
| }; | |
| void produce(struct queue *q, struct task *t) { | |
| pthread_mutex_lock(&q->mu); | |
| /* If the queue is full, wait */ | |
| while (q->num_tasks >= NUM_WORKER_THREADS) { | |
| pthread_cond_wait(&q->condvar, &q->mutex); | |
| } | |
| /* Add task to the queue */ | |
| q->tasks[q->num_tasks] = *t; | |
| q->num_tasks++; | |
| /* Notify workers that queue is not empty */ | |
| pthread_cond_signal(&q->condvar); | |
| pthread_mutex_unlock(&q->mutex); | |
| } | |
| void consume(struct queue *q, struct task *t) { | |
| pthread_mutex_lock(&q->mu); | |
| /* If the queue is empty, wait */ | |
| while (q->num_tasks == 0) { | |
| pthread_cond_wait(&q->condvar, &q->mutex); | |
| } | |
| /* Grab task from the queue */ | |
| *t = q->tasks[q->num_tasks] = *t; | |
| q->num_tasks--; | |
| /* Notify master */ | |
| pthread_cond_signal(&q->condvar); | |
| pthread_mutex_unlock(&q->mutex); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment