线程中建立新线程,退出机制
程序:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
pthread_t son_t = 0;
void cleanup(void*)
{
if(!pthread_cancel(son_t)) //如果不在退出test_pthread线程前,退出test_son线程的话,即使test_pthread退出,test_son也还会存在.
{
pthread_join(son_t,NULL);
system("ps -mp `ps | grep main | awk '{print $1}'`"); //这一句是找出本进程的所有线程.
}
printf("clean\n");
}
void son_cleanup(void*)
{
printf("son clean\n");
}
void* test_son(void*)
{
pthread_cleanup_push(son_cleanup,NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
// pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
// pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
while(1)
{
printf("son\n");
sleep(1);
}
pthread_cleanup_pop(0);
return NULL;
}
void* test_pthread(void*)
{
pthread_cleanup_push(cleanup,NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
// pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
// pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
while(1)
{
int a = 1;
a = a;
if(son_t == 0)pthread_create(&son_t,0,test_son,0);
system("ps -mp `ps | grep main | awk '{print $1}'`");
sleep(5);
// printf("aaa\n");
// pthread_testcancel();
// printf("bbb\n");
// printf("ccc\n");
// sleep(5);
// printf("ddd\n");
// pthread_testcancel();
// system("ls");
}
pthread_cleanup_pop(0);
return NULL;
}
int main()
{
pthread_t m_t;
pthread_create(&m_t,0,test_pthread,NULL);
int counter = 0;
while(++counter < 10)
{
printf("counter:%d\n",counter);
if(counter == 3)
{
if(!pthread_cancel(m_t))
{
pthread_join(m_t,NULL);
system("ps -mp `ps | grep main | awk '{print $1}'`");
}
}
sleep(1);
}
}
运行结果:
[user:lib_hdmanage] ./example/main.i386.elf
counter:1
son
PID TTY TIME CMD
13052 pts/7 00:00:00 main.i386.elf
- - 00:00:00 - //主线程
- - 00:00:00 - //test_pthread
- - 00:00:00 - //test_son
counter:2
son
counter:3
son clean
PID TTY TIME CMD
13052 pts/7 00:00:00 main.i386.elf
- - 00:00:00 - //主线程
- - 00:00:00 - //test_pthread
clean
PID TTY TIME CMD
13052 pts/7 00:00:00 main.i386.elf
- - 00:00:00 -//主线程
counter:4
counter:5
counter:6
counter:7
counter:8
counter:9