Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include "queue.h"
- /* Struct containing entries to go in the queue
- * TODO: add you're fields
- * TODO: name sensibly
- */
- typedef struct queue_entry
- {
- TAILQ_ENTRY(queue_entry) link;
- // Add working fields
- int data;
- } queue_entry_t; // Name appropriately
- /* Queue, Cond to signal data and Mutex to protect it */
- static TAILQ_HEAD(,queue_entry) queue;
- static pthread_mutex_t mutex;
- static pthread_cond_t cond;
- /*
- * Basic pattern for a queue driven thread
- */
- void *a_thread ( void *aux )
- {
- queue_entry_t *qe;
- pthread_mutex_lock(&mutex);
- while (1) { // do you need an exit condition - probably not
- /* Get entry from queue */
- qe = TAILQ_FIRST(&queue);
- if (!qe) { // Queue empty
- pthread_cond_wait(&cond, &mutex); // Note: this will unlock mutex
- // on entry and lock on exit
- continue; // Go back to get entry (or if exit)
- }
- TAILQ_REMOVE(&queue, qe, link); // Remove entry and we're done with Q
- pthread_mutex_unlock(&mutex); // now other threads can add while
- // we process
- // TOOD: DO SOME WORK
- printf("DATA: %d\n", qe->data);
- }
- // Cannot reach here unless you have exit condition
- return NULL;
- }
- /*
- * Initialise
- */
- void init ( void )
- {
- pthread_t tid; // you probably don't need to keep this
- pthread_mutex_init(&mutex, NULL); // Use default config
- pthread_cond_init(&cond, NULL); // ditto
- /* Start thread - presumably permanently active */
- pthread_create(&tid, NULL, a_thread, NULL); // last param is passed as aux
- // as this is single global
- // you can probably use global
- // vars
- }
- /*
- * Add data to the queue
- *
- * TODO: you can either have user pass in just the "data"
- * or a full queue_entry_t but you'd need to define struct in header
- */
- void add ( int data )
- {
- /* Create entry */
- queue_entry_t *qe = calloc(1, sizeof(queue_entry_t));
- qe->data = data;
- /* Insert */
- pthread_mutex_lock(&mutex);
- TAILQ_INSERT_TAIL(&queue, qe, link);
- pthread_cond_signal(&cond); // tell thread data is available
- pthread_mutex_unlock(&mutex);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement