ptg10805159
Section 21.5 Source Code 829
520 /*
521 * Cancellation routine for the worker thread.
522 *
523 * LOCKING: acquires and releases workerlock.
524 */
525 void
526 client_cleanup(void *arg)
527 {
528 struct worker_thread *wtp;
529 pthread_t tid;
530 tid=(pthread_t)((long)arg);
531 pthread_mutex_lock(&workerlock);
532 for (wtp = workers; wtp != NULL; wtp = wtp->next) {
533 if (wtp->tid == tid) {
534 if (wtp->next != NULL)
535 wtp->next->prev=wtp->prev;
536 if (wtp->prev != NULL)
537 wtp->prev->next=wtp->next;
538 else
539 workers=wtp->next;
540 break;
541 }
542 }
543 pthread_mutex_unlock(&workerlock);
544 if (wtp != NULL) {
545 close(wtp->sockfd);
546 free(wtp);
547 }
548 }
[520 – 542] The client_cleanup function is the thread cleanup handler for the
worker threads that communicate with client commands. This function is
called when the thread callspthread_exit,callspthread_cleanup_pop
with a nonzeroargument, or responds to a cancellation request. The
argument is the thread ID of the thread terminating.
We lock theworkerlockmutex and search the list of worker threads until
we find a matching thread ID. When we find a match, we remove the
worker thread structurefromthe list and stop the search.
[543 – 548] We unlock theworkerlockmutex, close the socket file descriptor used by
the thread to communicate with the client, and free the memory backing the
worker_threadstructure.
Since we try to acquiretheworkerlock mutex, if a thread reaches a
cancellation point while thekill_workersfunction is still walking the list,
we will have to wait untilkill_workersreleases the mutex before we can
proceed.