Debian Codegraph @

listings/chapter-4/cleanup.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
10 /* Allocate a temporary buffer. */
11
12 void* allocate_buffer (size_t size)
13 {
14 return malloc (size);
15 }
16
17 /* Deallocate a temporary buffer. */
18
19 void deallocate_buffer (void* buffer)
20 {
21 free (buffer);
22 }
23
24 void do_some_work ()
25 {
26 /* Allocate a temporary buffer. */
27 void* temp_buffer = allocate_buffer (1024);
28 /* Register a cleanup handler for this buffer, to deallocate it in
29 case the thread exits or is cancelled. */
30 pthread_cleanup_push (deallocate_buffer, temp_buffer);
31
32 /* Do some work here that might call pthread_exit or might be
33 cancelled... */
34
35 /* Unregister the cleanup handler. Since we pass a non-zero value,
36 this actually performs the cleanup by calling
37 deallocate_buffer. */
38 pthread_cleanup_pop (1);
39 }