|
#include <pthread.h>
#include <stdio.h>
?
?
// pthread_cleanup_push and pthread_cleanup_pop should be called in pairs at the same lexical nesting level
// they are implemented with ‘{‘ ‘}‘
?
// pthread_cleanup_pop with non-zero argument/pthread_cancel/pthread_exit
// will cause the remained handler to be popped and executed
?
#define ERROR printf("error @ %s line %d\n", __FILE__, __LINE__ );
?
void thread_cleanup( void *arg )
{
// __func__ can be used instead
printf("%s is called\n", __FUNCTION__ );
}
?
void* threadfn( void *data )
{
pthread_cleanup_push( thread_cleanup, NULL );
?
// sleep是一個可以執行線程取消的函數,稱為取消點【see man 7 pthreads】;
sleep( 20 );
?
pthread_cleanup_pop( 1 );
}
?
int main(int argc, char const *argv[])
{
pthread_t thread;
?
if ( pthread_create( &thread, NULL, threadfn, NULL) )
{
ERROR;
return -1;
}
?
sleep( 1 );
?
// cancel the thread before it exits
if( pthread_cancel( thread ) )
{
ERROR;
return -1;
}
?
// wait for thread to complete it‘s cleanup
if( pthread_join( thread, NULL ) )
{
ERROR;
return -1;
}
?
printf("Done!\n");
?
return 0;
} |