Debian Codegraph @

listings/chapter-4/job-queue3.c

raw
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 #include <semaphore.h>
10
11 struct job {
12 /* Link field for linked list. */
13 struct job* next;
14
15 /* Other fields describing work to be done... */
16 };
17
18 /* A linked list of pending jobs. */
19 struct job* job_queue;
20
21 extern void process_job (struct job*);
22
23 /* A mutex protecting job_queue. */
24 pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
25
26 /* A semaphore counting the number of jobs in the queue. */
27 sem_t job_queue_count;
28
29 /* Perform one-time initialization of the job queue. */
30
31 void initialize_job_queue ()
32 {
33 /* The queue is initially empty. */
34 job_queue = NULL;
35 /* Initialize the semaphore which counts jobs in the queue. Its
36 initial value should be zero. */
37 sem_init (&job_queue_count, 0, 0);
38 }
39
40 /* Process queued jobs until the queue is empty. */
41
42 void* thread_function (void* arg)
43 {
44 while (1) {
45 struct job* next_job;
46
47 /* Wait on the job queue semaphore. If its value is positive,
48 indicating that the queue is not empty, decrement the count by
49 one. If the queue is empty, block until a new job is enqueued. */
50 sem_wait (&job_queue_count);
51
52 /* Lock the mutex on the job queue. */
53 pthread_mutex_lock (&job_queue_mutex);
54 /* Because of the semaphore, we know the queue is not empty. Get
55 the next available job. */
56 next_job = job_queue;
57 /* Remove this job from the list. */
58 job_queue = job_queue->next;
59 /* Unlock the mutex on the job queue, since we're done with the
60 queue for now. */
61 pthread_mutex_unlock (&job_queue_mutex);
62
63 /* Carry out the work. */
64 process_job (next_job);
65 /* Clean up. */
66 free (next_job);
67 }
68 return NULL;
69 }
70
71 /* Add a new job to the front of the job queue. */
72
73 void enqueue_job (/* Pass job-specific data here... */)
74 {
75 struct job* new_job;
76
77 /* Allocate a new job object. */
78 new_job = (struct job*) malloc (sizeof (struct job));
79 /* Set the other fields of the job struct here... */
80
81 /* Lock the mutex on the job queue before accessing it. */
82 pthread_mutex_lock (&job_queue_mutex);
83 /* Place the new job at the head of the queue. */
84 new_job->next = job_queue;
85 job_queue = new_job;
86
87 /* Post to the semaphore to indicate another job is available. If
88 threads are blocked, waiting on the semaphore, one will become
89 unblocked so it can process the job. */
90 sem_post (&job_queue_count);
91
92 /* Unlock the job queue mutex. */
93 pthread_mutex_unlock (&job_queue_mutex);
94 }