115. 多线程 - 线程取消

延时到取消点,才会执行取消动作

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
 
void *thread_fun(void *arg)
{
	int stateval;
	int typeval;
	stateval = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);   //新线程将自己设置为不可取消的状态
	if(stateval != 0)
	{
		printf("set cancel state failed\n");
	}
	printf("I`m new thread\n");
	sleep(4);    //方便主线程对其进行操作
 
	printf("about to cancel\n");
	stateval = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);  //设置自己为可取消的状态。
	if(stateval != 0)\
	{
		printf("set cancel state failed\n");
	}

	printf("first cancel point\n");
	printf("second cancel point\n");
 
	return (void *)20;    //设置退出码是20
}
 
int main()
{
	pthread_t tid;
	int err,cval,jval;
	void *rval;
 
	err = pthread_create(&tid,NULL,thread_fun,NULL);   //线程操作,成功会返回0  新线程去执行thread_fun
	if(err != 0)
	{
		printf("create thread failed\n");
		return 0;
	}
	sleep(2);
 
	cval = pthread_cancel(tid);
	if(cval != 0)
	{
		printf("cancel thread failed\n");
	}
	jval = pthread_join(tid,&rval);   //join函数有两个参数,新线程的tid,与新线程的退出码。 join函数之后,又转向新线程去执行
	printf("new thread exit code is %ls\n",(int *)rval);
	return 0;
}
book@100ask:~/C_coding/0204$ sudo gcc -o pthread pthread.c -lpthread

book@100ask:~/C_coding/0204$ ./pthread
I`m new thread
about to cancel
Segmentation fault (core dumped)

 

book@book:~/Linux_C$ sudo gcc thread_cancel.c -lpthread -o thread_cancel

book@book:~/Linux_C$ ./thread_cancel 
I`m new thread
about to cancel
Segmentation fault (core dumped)
book@book:~/Linux_C$ cat thread_cancel.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
 
void *thread_fun(void *arg)
{
	int stateval;
	int typeval;
	stateval = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
	if(stateval != 0)
	{
		printf("set cancel state failed\n");
	}
	printf("I`m new thread\n");
	sleep(4);

	printf("about to cancel\n");
	stateval = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
	if(stateval != 0)\
	{
		printf("set cancel state failed\n");
	}
	typeval = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
	if(typeval != 0)
	{
		printf("set cancel type failed\n");
	}

	printf("first cancel point\n");
	printf("second cancel point\n");

	return (void *)20;     as function "void *thread_fun1(void *arg)" required return void *, so here return 1, 1 need to transver to (void *)
}

int main()
{
	pthread_t tid;
	int err,cval,jval;
	void *rval;

	err = pthread_create(&tid,NULL,thread_fun,NULL);
	if(err != 0)
	{
		printf("create thread failed\n");
		return 0;
	}
	sleep(2);

	cval = pthread_cancel(tid);
	if(cval != 0)
	{
		printf("cancel thread failed\n");
	}
	jval = pthread_join(tid,&rval);
	printf("new thread exit code is %ls\n",(int *)rval);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值