主进程中如何退出pthread_create创建的线程?

cancel有两种模式,Defered或者Asynchronous,
Defered模式线程只在某些cancel点检查自己是否需要cancel,
Async模式则是立即cancel。
当然两种模式下,通过pthread_cleanup_push()建立的cleanup还是会执行的。

一个Async模式的例子。


#include <stdarg.h>

#include <stdio.h>



#include <pthread.h>



static pthread_t child;



static void fatal(const char *fmt, ...)

{

va_list arglist;



fprintf(stderr, "FATAL: ");



va_start(arglist, fmt);

vfprintf(stderr, fmt, arglist);

fputs("/n", stderr);

va_end(arglist);



exit(1);

}



static void say(const char *fmt, ...)

{

va_list arglist;



va_start(arglist, fmt);

vfprintf(stderr, fmt, arglist);

fputs("/n", stderr);

va_end(arglist);

}



static void child_cleanup(void *arg)

{

say(" [-child-] Cleanup routine called");

}



static void *thread_func(void *arg)

{

int i=0;



if(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL))

fatal("set cancel type failed");



pthread_cleanup_push(&child_cleanup, NULL);



say(" [-child-] Entering dead loop...");

while(1){

i++;

}



pthread_cleanup_pop(0);



return NULL;

}



int main()

{

void *pe = NULL;



say("Creating child thread...");

if(pthread_create(&child, NULL, thread_func, NULL))

fatal("Failed to create a thread");



/* Wait for child to set cancel type */

/* Use pthread_barrier_wait() to guarantee that.*/

sleep(3);



say("Cancelling child...");

if(pthread_cancel(child))

fatal("Failed to cancel child thread");



say("Joining child...");

if(pthread_join(child, &pe))

fatal("Failed to join the child thread");



if(pe == PTHREAD_CANCELED){

say("Child is really Canceled");

}



say("Main thread exiting...");

return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值