Linux多线程实例练习 - pthread_cancel()

时间:2023-03-08 23:33:13
Linux多线程实例练习 - pthread_cancel()

Linux多线程实例练习 - pthread_cancel

1、代码 xx_pthread_cancel.c

#include <pthread.h>
#include <stdio.h>
#include <unistd.h> #define debug_Msg(fmt, arg...)\
do{\
printf("%s %d : ", __FILE__, __LINE__);\
printf(fmt, ##arg);\
}while() #define ENABLE_X
char * pe = "enable return";
void * state_Enable(void *arg)
{
int i = ;
int iExit = ;
while(i < && iExit == )
{
debug_Msg("state Enable : [%d]\n", i);
i++;
sleep();
}
char * p = pe;
return p;
} #define DISABLE_X
char * pd = "disable return";
void * state_Disable(void * arg)
{
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
int i = ;
int iExit = ;
while(i < && iExit == )
{
debug_Msg("state Disable : [%d]\n", i);
i++;
sleep();
}
char * p = pd;
return p;
} int main()
{
#ifdef ENABLE_X
pthread_t pid;
pthread_create(&pid, NULL, state_Enable, NULL);
sleep();
pthread_cancel(pid);
void * p = NULL;
printf("init with : [%08X]\n", (unsigned int)p);
pthread_join(pid, &p);
printf("pe addr : [%08X]\n", (unsigned int)pe);
printf("over with : [%08X]\n", (unsigned int)p);
#endif #ifdef DISABLE_X
pthread_t pDis;
pthread_create(&pDis, NULL, state_Disable, NULL);
sleep();
pthread_cancel(pDis);
p = NULL;
printf("init with : [%08X]\n", (unsigned int)p);
pthread_join(pDis, &p);
printf("pd addr : [%08X]\n", (unsigned int)pd);
printf("over with : [%08X]\n", (unsigned int)p);
#endif
}

2、CentOS 编译通过

g++ -g -c -o xx_pthread_cancel.o xx_pthread_cancel.c
g++ -g -o xx_pthread_cancel xx_pthread_cancel.o -lpthread

3、运行结果

$ ./xx_pthread_cancel
xx_pthread_cancel.c : state Enable : []
xx_pthread_cancel.c : state Enable : []
xx_pthread_cancel.c : state Enable : []
init with : []
pe addr : []
over with : [FFFFFFFF]
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
init with : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
xx_pthread_cancel.c : state Disable : []
pd addr : []
over with : []