Linux線程之退出(十二)
- 1.線程的退出
- 2.參考代碼
1.線程的退出
程序中我們可以調用exit函數或exit函數來結束程序,在一個線程中我們可以通過以下三種在不終止整個程序的情況下停止它的控制流。 線程從執行函數中傳回。 線程調用pthreadexit退出線程。 線程可以被同一程序中的其它線程取消。
功能:
退出調用線程。一個程序中的多個線程是共享該程序的資料段,是以,通常線程退出後所占用的資源并不會釋放。
參數:
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)