Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 21.5 Source Code 821


254 jp->jobid=jobid;
255 jp->next=NULL;
256 pthread_mutex_lock(&joblock);
257 jp->prev=jobtail;
258 if (jobtail == NULL)
259 jobhead=jp;
260 else
261 jobtail->next=jp;
262 jobtail=jp;
263 pthread_mutex_unlock(&joblock);
264 pthread_cond_signal(&jobwait);
265 }

266 /*
267 * Replace a job back on the head of the list.
268 *
269 * LOCKING: acquires and releases joblock.
270 */
271 void
272 replace_job(struct job *jp)
273 {
274 pthread_mutex_lock(&joblock);
275 jp->prev=NULL;
276 jp->next=jobhead;
277 if (jobhead == NULL)
278 jobtail=jp;
279 else
280 jobhead->prev=jp;
281 jobhead=jp;
282 pthread_mutex_unlock(&joblock);
283 }

[254 – 265] We save the job ID and lock thejoblockmutex to gain exclusive access to
the linked list of print jobs.We are about to add the new job structure to the
end of the list.We set the new structure’s previous pointer to the last job on
the list. If the list is empty, we setjobheadto point to the new structure.
Otherwise, we set the next pointer in the last entry on the list to point to the
new structure. Then we setjobtailto point to the new structure. We
unlock the mutex and signal the printer thread that another job is available.
[266 – 283] Thereplace_jobfunction is used to insert a job at the head of the pending
job list.We acquirethejoblockmutex, set the previous pointer in thejob
structuretoNULL,and set the next pointer in thejobstructure to point to
the head of the list. If the list is empty, we setjobtailto point to thejob
structure we are replacing. Otherwise, we set the previous pointer in the
firstjobstructure on the list to point to thejobstructure we are replacing.
Then we set thejobheadpointer to thejobstructureweare replacing.
Finally, we release thejoblockmutex.
Free download pdf