结束线程方法:
-
线程返回
-
调用 pthread_exit 函数(自杀)
-
调用 pthread_cancel 函数(他杀)
当所杀的线程内调用了pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
则调用pthread_cancel 函数没有作用
pthread_setcancelstate意为对Cancel信号的反应(disable表忽略)
-
调用一个全局变量
注意:在 main 函数中,return 语句和 pthread_exit 函数具有不同的效果,return 语句执行后进程也会结束,进程内部的所有线程自然强制结束,但 pthread_exit 函数只会结束主线程,并不会结束其他线程。
在普通线程的线程函数中,return 语句和 pthread_exit 函数基本差不多,只不过 pthread_exit 函数还会调用一下之前已经注册的线程清理函数。
volitile:C 语言关键字,作用就是告诉编译器取消对变量的优化,每次访问都从内存中存取变量。尤其是在多个线程都需要频繁访问一个全局变量时,强烈建议使用该关键字修饰变量。
编译器优化常用的方法有:将内存变量缓存到寄存器;调整指令顺序充分利用CPU指令流水线,常见的是重新排序读写指令。对常规内存进行优化的时候,这些优化是透明的,而且效率很好。
volitile表明某个变量的值可能在外部被改变,因此对这些变量的存取不能缓存到寄存器,每次使用时需要重新存取。
register:C 语言关键字,建议编译器将变量设置为寄存器变量。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* thr_fun1(void* arg);
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, thr_fun1, NULL);
sleep(3);
pthread_cancel(tid);
pthread_join(tid,NULL);
return 0;
}
void *thr_fun1(void* arg)
{
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);//忽略他杀请求
while(1)
{
printf("hello\n");
sleep(1);
}
return NULL;
}