线程中建立新线程,退出机制

线程中建立新线程,退出机制

程序:

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值