线程如何获取另外主动退出的线程的传出指针


1    线程退出函数


             #include <pthread.h>


             void pthread_exit(void *value_ptr);


2    通过线程id等待指定线程退出的线程函数。


        #include <pthread.h>


       int pthread_join(pthread_t thread, void **value_ptr);


3    获取线程自身的线程id


        #include <pthread.h>


       pthread_t pthread_self(void);


下面直接附上代码。


线程2等待线程1退出。并获取 pthread_exit传过来的指针

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/statfs.h>
#include <pthread.h>
//主动关闭其他线程。
//获取指定线程的退出状态

static void * proc_func_exit(void *);
static void * proc_func_join(void *);
int main()
{
   pthread_t th1 = -1;
   pthread_t th2 = -1;
   int ret = -1;

   ret = pthread_create(&th1,NULL,proc_func_exit,NULL);
   
   if(0 != ret)
   {
	return -1;
   }

   ret = pthread_create(&th2,NULL,proc_func_join,&th1);

   if(0 != ret)
   {
	return -1;
   }
   while(1)
   {
       sleep(0xfff);
   }
   
   return 0;
}


static void * proc_func_exit(void *pArg)
{

    // 获取自身的线程id
    pthread_t pth_id = -1;
    char *str = NULL;
    str = (char *)malloc(100);

     if(NULL == str)
    {
	return (void*)0;
    }
    pth_id = pthread_self();

    printf("\n*** pthread_id = %d****",pth_id);
    snprintf(str,100,"I am Exit! pthread_id = %d",pth_id );

    //线程退出  pthread_exit

    pthread_exit((void *)str);
    
    return (void *)0;
}

static void * proc_func_join(void *pArg)
{

    char *str = NULL;
    pthread_t pth_id = -1;

    if(pArg == NULL)
    {
	return (void *)0;
    }

    pth_id = *((pthread_t *)(pArg));
    pthread_join(pth_id ,&str);

    if(str != NULL)
    {
        printf("\nRecv:%s\n",str);
        free(str);
    }

    return (void *)0;

}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值