linux 所有线程结束,linux多线程的线程结束和提前结束

#include

#include

#include

#include

void *thread1(void *ptr)

{

//void *status1;

printf(" this is thread1, tid is %lu\n",

pthread_self());

sleep(5); //pthread_exit(status1);

}

void *thread2(void *ptr)

{

int ret4;

sleep(1); ret4 =

pthread_cancel(*((pthread_t*)ptr));

if(ret4<0)

printf("can not cancel thread %lu\n",

*((pthread_t*)ptr));

else

printf("has cancel the thread

%lu\n",*((pthread_t*)ptr));

}

int main(int argc, char** argv) {

pthread_t tid1,tid2;

int ret1,ret2,ret3;

int time1,time2;

void* status;

time1 = 30;

ret1=

pthread_create(&tid1,NULL,thread1,(void*)time1);

ret2=

pthread_create(&tid2,NULL,thread2,(void*)&tid1); ret3=

pthread_join(tid1,&status); if(status == PTHREAD_CANCELED)

{

printf(" thread1 is canceled!\n");

}

else

{

printf(" thread1 run 5 seconds, then

end!\n");

}

sleep(10);

return (EXIT_SUCCESS);

}

结果:

this is thread1, tid is 3083447184

has cancel the thread 3083447184

//pthread2在执行pthread_cancel(pthread1)时,pthread1还处于sleep状态,故可以cancel

thread1 is canceled!//pthread1的状态是cancel

如果在thread2中sleep(6)秒,则会

this is thread1, tid is 3083447184

thread1 run 5 seconds,then

end!//pthread2在执行pthread_cancel(pthread1)之前,pthread1已经结束并返回给主线程

has cancel the thread 3083447184//仍可以cancel

与pthread_cancel函数有关系

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值