延时到取消点,才会执行取消动作
#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;
}