Linux系统编程之线程退出

pthread_exit函数

  • 功能:将单个线程退出
  • void pthread_exit(void *retval);
  • 参数:retval表示线程退出状态,通常传NULL
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>

void *thrd_func(void*arg)
{
 prrintf("In thread;thread id=%lu,pid=%d\n",pthread_self(),getpid());//子线程id
 return NULL;
}
  
int main()
{
  pthread_t tid;
  int ret;
  printf("In main 1:thread id=%lu,pid=%u\n",pthread_self(),getpid());//主控线程id
  ret=pthread_create(&tid,NULL,thrd_func,NULL);//主控线程
  if(ret!=0)
  {
     printf("pthread_create error\n");
     exit(1);
  }
  printf("In main 2:thread id=%lu,pid=%u\n",pthread_self(),getpid());
 pthread_exit(NULL);//主控线程退出,子线程不受影响
}

输出:

在这里插入图片描述

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
void *thrd_func(void*arg)
{
  int i=*(int*)arg);
  sleep(i);//为了使创建的线程有先后顺序
 prrintf("I'吗%d thread;thread id=%lu,pid=%d\n",i+1,pthread_self(),getpid());//子线程id
 return NULL;
}
  
int main()
{
  pthread_t tid;
  int ret,i;
  
  for(i=0;i<5;i++)
  {
    pthread_create(&tid,NULL,thrd_func,void *&i);//主控线
    
  }
  printf("I am main,and I am not a process,I'm a thread!\n""main_thread_ID=%lu",pthread_self());
  pthread_exit(NULL);//主控线程退出,子线程不受影响

}

输出:
在这里插入图片描述
从这里可以看出,用循环因子区分子线程,不是很可取

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值