Linux multithreaded instance Exercise-Pthread_cancel
1. Code XX_PTHREAD_CANCEL.C
#include <pthread.h>#include<stdio.h>#include<unistd.h>#defineDebug_msg (FMT, arg ...) Do{printf ("%s%d:", __file__, __line__); printf (FMT, # #arg); } while(0)#defineEnable_xChar* PE ="Enable return";void* State_enable (void*Arg) { inti =0; intIexit =0; while(I <Ten&& Iexit = =0) {debug_msg ("State Enable: [%d]\n", i); I++; Sleep (1); } Char* p =PE; returnp;}#defineDisable_xChar* PD ="Disable return";void* State_disable (void*Arg) {pthread_setcancelstate (pthread_cancel_disable, NULL); inti =0; intIexit =0; while(I <Ten&& Iexit = =0) {debug_msg ("State Disable: [%d]\n", i); I++; Sleep (1); } Char* p =PD; returnp;}intMain () {#ifdef enable_x pthread_t pid; Pthread_create (&pid, NULL, state_enable, NULL); Sleep (3); Pthread_cancel (PID); void* p =NULL; printf ("init with: [%08x]\n", (unsignedint) (p); Pthread_join (PID,&p); printf ("pe addr: [%08x]\n", (unsignedint) (PE); printf ("Over with : [%08x]\n", (unsignedint) (p);#endif#ifdef disable_x pthread_t Pdis; Pthread_create (&Pdis, NULL, state_disable, NULL); Sleep (3); Pthread_cancel (Pdis); P=NULL; printf ("init with: [%08x]\n", (unsignedint) (p); Pthread_join (Pdis,&p); printf ("PD addr: [%08x]\n", (unsignedint) PD); printf ("Over with : [%08x]\n", (unsignedint) (p);#endif}
2, CentOS compiled by
g++-g-c-o xx_pthread_cancel.o xx_pthread_cancel.c g+ +-g-o xx_pthread_cancel xx_pthread_cancel.o-lpthread
3. Operation Result
$ ./Xx_pthread_cancel xx_pthread_cancel.c +: State Enable: [0]xx_pthread_cancel.c +: State Enable: [1]xx_pthread_cancel.c +: State Enable: [2]init with: [00000000]pe addr: [08048959]over with: [Ffffffff]xx_pthread_cancel.c $: State Disable: [0]xx_pthread_cancel.c $: State Disable: [1]xx_pthread_cancel.c $: State Disable: [2]init with: [00000000]xx_pthread_cancel.c $: State Disable: [3]xx_pthread_cancel.c $: State Disable: [4]xx_pthread_cancel.c $: State Disable: [5]xx_pthread_cancel.c $: State Disable: [6]xx_pthread_cancel.c $: State Disable: [7]xx_pthread_cancel.c $: State Disable: [8]xx_pthread_cancel.c $: State Disable: [9]pd addr: [08048968]over with: [08048968]
Linux multithreaded Instance Exercise-Pthread_cancel ()