1.线程的退出
进程中我们可以调用exit函数或exit函数来结束进程,在一个线程中我们可以通过以下三种在不终止整个进程的情况下停止它的控制流。 线程从执行函数中返回。 线程调用pthreadexit退出线程。 线程可以被同一进程中的其它线程取消。
void pthread_exit(void *retval);
功能:
退出调用线程。一个进程中的多个线程是共享该进程的数据段,因此,通常线程退出后所占用的资源并不会释放。
参数:
retval:存储线程退出状态的指针。
返回值:
无
2.参考代码
//=============================================================================
// File Name : thread_exit.c
// Author : FengQQ
//
// Description : 线程退出
// Annotation : 退出调用线程。一个进程中的多个线程是共享该进程的数据段,
// 因此,通常线程退出后所占用的资源并不会释放。
//
// Created by FengQQ. 2020-10-04
//=============================================================================
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
//---------------线程入口函数---------------
void *pthread_callback(void *arg)
{
int i = 0;
while(1)
{
printf("I am pthread run\r\n");
sleep(1);
if(5 == i++)
{
pthread_exit(NULL); //等待6s,线程退出
}
}
return 0;
}
int main(int argc,char *argv[])
{
int ret;
pthread_t ptid;
ret = pthread_create(&ptid,NULL,pthread_callback,NULL); //创建线程
if(ret != 0)
{
printf("create new pthread failed...\r\n");
return -1;
}
ret = pthread_join(ptid,NULL); //回收线程资源
if(ret != 0)
{
printf("pthread join failed...\r\n");
}
printf("pthread join success\r\n");
return 0;
}
Linux线程之取消(十三)
链接: link.(https://blog.csdn.net/qq_39721016/article/details/120243462?spm=1001.2014.3001.5502)