我们知道在进程中可以使用exit或者_exit来结束进程,线程可以使用以下三种方式停止控制流: - 线程从执行函数返回 - 线程中调用pthread_exit函数退出线程 - 线程可以被同一进程的其它线程取消
1.pthread_exit pthread_exit(void *ptr) 函数使线程退出,并返回一个空指针类型的值。
#include <pthread.h>
void pthread_exit(void *ptr);
参数: - prt:存储线程退出状态的指针
注意:pthread_exit执行后线程退出,但是并不释放线程资源。
实例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thr_fn(void *arg)
{
static char *buff = "this son thread has quit...";
int i;
printf("son thread is running...\n");
for (i = 0; i < 10; i++)
{
printf("i=%d\n", i);
sleep(1);
if (i == 5)
{
pthread_exit(buff); //线程退出
}
}
}
int main(int argc, char const *argv[])
{
printf("main thread is running....\n");
pthread_t thread;
if (pthread_create(&thread, NULL, thr_fn, NULL) != 0)
{
perror("error to pthread_create:");
exit(-1);
}
char *str;
if (pthread_join(thread, (void **)&str) != 0)
{
perror("error to join:");
exit(-1);
}
printf("str=%s\n", str);
printf("main thread will exit....\n");
return 0;
}
执行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
main thread is running....
son thread is running...
i=0
i=1
i=2
i=3
i=4
i=5
str=this son thread has quit...
main thread will exit....