| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <malloc.h> |
| 8 |
#include <pthread.h> |
| 9 |
|
| 10 |
struct job { |
| 11 |
/* Link field for linked list. */ |
| 12 |
struct job* next; |
| 13 |
|
| 14 |
/* Other fields describing work to be done... */ |
| 15 |
}; |
| 16 |
|
| 17 |
/* A linked list of pending jobs. */ |
| 18 |
struct job* job_queue; |
| 19 |
|
| 20 |
extern void process_job (struct job*); |
| 21 |
|
| 22 |
/* A mutex protecting job_queue. */ |
| 23 |
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; |
| 24 |
|
| 25 |
/* Process queued jobs until the queue is empty. */ |
| 26 |
|
| 27 |
void* thread_function (void* arg) |
| 28 |
{ |
| 29 |
while (1) { |
| 30 |
struct job* next_job; |
| 31 |
|
| 32 |
/* Lock the mutex on the job queue. */ |
| 33 |
pthread_mutex_lock (&job_queue_mutex); |
| 34 |
/* Now it's safe to check if the queue is empty. */ |
| 35 |
if (job_queue == NULL) |
| 36 |
next_job = NULL; |
| 37 |
else { |
| 38 |
/* Get the next available job. */ |
| 39 |
next_job = job_queue; |
| 40 |
/* Remove this job from the list. */ |
| 41 |
job_queue = job_queue->next; |
| 42 |
} |
| 43 |
/* Unlock the mutex on the job queue, since we're done with the |
| 44 |
queue for now. */ |
| 45 |
pthread_mutex_unlock (&job_queue_mutex); |
| 46 |
|
| 47 |
/* Was the queue empty? If so, end the thread. */ |
| 48 |
if (next_job == NULL) |
| 49 |
break; |
| 50 |
|
| 51 |
/* Carry out the work. */ |
| 52 |
process_job (next_job); |
| 53 |
/* Clean up. */ |
| 54 |
free (next_job); |
| 55 |
} |
| 56 |
return NULL; |
| 57 |
} |
| 58 |
|