thrqueue.c is a blob of C which provides a thread-safe queue, allowing you to pass void pointers between pthreads easily.
Producer threads enqueue items and optionally block if the work queue is too long. Worker threads dequeue items and block if there is no work to be done.
An example test program is included in the source code. Basic operation:
// gcc -Wall -std=c99 -pthread -o test test.c thrqueue.c
#include <stdio.h>
#include <pthread.h>
#include "thrqueue.h"
struct Queue *q;
void *worker(void *args) {
char *work;
while ((work = queue_deq(q)))
printf("Got: '%s'\n", work);
return NULL;
}
int main(void) {
q = queue_init();
queue_limit(q, 10); // no more than 10 pending items
pthread_t worker_thread;
pthread_create(&worker_thread, NULL, worker, NULL);
// Feed workers work, blocking if workers fall behind
char *foo = "moo";
for (int i=0; i < 20; i++)
queue_enq(q, foo);
// Signal workers to quit
queue_enq(q, NULL);
// Wait for workers to exit, then free the queue
pthread_join(worker_thread, NULL);
queue_destroy(q);
return 0;
}
| Filename | Filesize | Last Modified |
|---|---|---|
| thrqueue.c | 6.39k | 2009-02-19 01:02 |
| thrqueue.h | 0.76k | 2009-02-19 11:02 |