示例 demo
最简单的 demo:
staticvoid*thread1_func(void*arg)
{inti=0;//abletobecancelpthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);for(i=0;;i++){printf("thread1%dn",i);sleep(1);}}intmain(intargc,char**argv){pthread_tt;void*res;pthread_create(&t,NULL,thread1_func,NULL);sleep(3);pthread_cancel(t);//cancelthread1pthread_join(t,&res);//waitthread1if(res==PTHREAD_CANCELED)printf("thread1wasterminatebycanceln");elseprintf("thread1wasnotterminatebycanceln");exit(EXIT_SUCCESS);}
为了突出重点,省略了检查返回值。
运行效果:
thread10
thread11thread12thread1wasterminatebycancel
主线程先创建线程 thread1虚拟主机 linuxlinux deepin,然后睡眠 3 秒后发出终止 thread1 的请求。
接收到终止请求后,thread1 会在合适的时机被终止掉。
主线程通过 pthread_join() 阻塞等待 thread1 退出。
几个要点线程终止的 4 种方式:
线程的执行函数返回了,这和 main() 函数结束类似。
线程调用了 pthread_exit() 函数,这和调用 exit() 返回类似。
线程被另一个线程通过 pthread_cancel() 函数取消,这和通过kill() 发送 SIGKILL 信号类似。
进程终止了,则进程中的所有线程也会终止。
取消某个线程的常规步骤
被取消的线程:
允许取消,pthread_setcancelstate(),参数可选值:
设置取消类型,pthread_setcanceltype(),参数可选值:
发起取消的线程:
发送取消要求,pthread_cancel(),发出取消请求后,pthread_cancel() 当即返回linux 判断线程是否在运行,不会等待目标线程的退出。
等待取消完成linux 判断线程是否在运行,pthread_join()。
哪些函数是取消点?
POSIX.1 指定了哪些函数一定是取消点:
点击查看大图
更多关于取消点的介绍:
$man7pthreads
Cancellationpoints...accept()aio_suspend()clock_nanosleep()close()...阅读开源软件 MJPG-streamer
MJPG-streamer 是什么?
简单地说,就是一个开源的流媒体服务器:
通过 mjpg-streamer,你可以通过 PC 浏览器访问到板子上的摄像头图像。
MJPG-streamer 是如何结束工作线程的?
MJPG-streamer 运行时一般会有 3 个线程: