ch4-cleanup

Chapter_4     tsd cxx-exit







cleanup.c     ALP, p. 74


#include <stdio.h> // for printf(), scanf(), fprintf(), stderr, NULL
#include <stddef.h> // for size_t
#include <malloc.h> // for malloc(), free()
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join(),
// pthread_cleanup_push(), pthread_cleanup_pop(), pthread_testcancel(),
// pthread_cancel(), pthread_exit()

void * allocate_buffer (size_t size);
void deallocate_buffer (void* buffer);
void * do_some_work (void * unused);

int main()
{
pthread_t thread;
pthread_create (&thread, NULL, &do_some_work, NULL);
// pthread_cancel(thread); // "Type a word: Deallocating buffer"
pthread_join (thread, NULL);

return 0;
}

void * allocate_buffer (size_t size)
{
return malloc (size);
}

void deallocate_buffer (void* buffer)
{
fprintf(stderr, "Deallocating buffer\n");
free (buffer);
}

void * do_some_work (void * unused)
{
/* Allocate a temporary buffer: */
void* temp_buffer = allocate_buffer (1024);
/* Register a cleanup handler for this buffer, to deallocate it in
case the thread exits or is cancelled: */
pthread_cleanup_push(deallocate_buffer, temp_buffer);
// pthread_cleanup_push(free, temp_buffer); // no "Deallocating buffer"

/* Do some work here that might call pthread_exit() or might be
cancelled... */
pthread_testcancel(); // cancelation points
printf("Type a word: ");
scanf("%s", (char *)temp_buffer);
printf("You typed: %s\n", (char *)temp_buffer);
// pthread_exit(NULL); // deallocate_buffer() is still called

/* Unregister the cleanup handler. Because we pass a nonzero value,
this actually performs the cleanup by calling deallocate_buffer(). */
pthread_cleanup_pop(1); // push and pop must be in the same scope

return NULL;
}

/*
gcc cleanup.c -o cleanup -lpthread
./cleanup
Type a word: Hello!
You typed: Hello!
Deallocating buffer
*/





Notes:

See also pthread_cleanup_push(3) on Linux_man-pages.
pthread_cleanup_push() and pthread_cleanup_pop() are implemented as macros and must be present in the same scope, meaning within the same brace (block) nesting level.









Chapter_4     tsd BACK_TO_TOP cxx-exit



Comments

Popular posts from this blog

Contents