#include <iostream>
#include <pthread.h>
using namespace std;
void *thread_function(void* arg);
int main(void)
{
int res;
pthread_t threadID;
void *thread_result;
res = pthread_create(&threadID, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread Create Failed!");
exit(EXIT_FAILURE);
}
sleep(3);
printf("Cancleing Thread...\n");
//线程终止,取消线程
res = pthread_cancel(threadID);
if (res != 0)
{
perror("Thread Cancel Failed!");
exit(EXIT_FAILURE);
}
printf("Waiting For Thread To Finished...\n");
res = pthread_join(threadID, &thread_result);
if (res != 0)
{
perror("Thread Join Failed!");
exit(EXIT_FAILURE);
}
printf("Thread Canceled!");
return(EXIT_SUCCESS);
}
void *thread_function(void* arg)
{
int i, res;
//取消状态 PTHREAD_CANCEL_ENABLE 允许线程接收取消请求
res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if (res != 0)
{
perror("Thread Setcancelstate Failed!");
exit(EXIT_FAILURE);
}
//设置取消类型 PTHREAD_CANCEL_DEFERRED
//接收到取消请求后,一直等待直到线程执行了下述函数之一后才采取行动
res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
if (res != 0)
{
perror("Thread Setcanceltype Failed!");
exit(EXIT_FAILURE);
}
printf("thread_function is running......\n");
for(i=0;i<10;i++)
{
printf("Thread is still running (%d) \n", i);
sleep(1);
}
pthread_exit(0);
#include <pthread.h>
using namespace std;
void *thread_function(void* arg);
int main(void)
{
int res;
pthread_t threadID;
void *thread_result;
res = pthread_create(&threadID, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread Create Failed!");
exit(EXIT_FAILURE);
}
sleep(3);
printf("Cancleing Thread...\n");
//线程终止,取消线程
res = pthread_cancel(threadID);
if (res != 0)
{
perror("Thread Cancel Failed!");
exit(EXIT_FAILURE);
}
printf("Waiting For Thread To Finished...\n");
res = pthread_join(threadID, &thread_result);
if (res != 0)
{
perror("Thread Join Failed!");
exit(EXIT_FAILURE);
}
printf("Thread Canceled!");
return(EXIT_SUCCESS);
}
void *thread_function(void* arg)
{
int i, res;
//取消状态 PTHREAD_CANCEL_ENABLE 允许线程接收取消请求
res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if (res != 0)
{
perror("Thread Setcancelstate Failed!");
exit(EXIT_FAILURE);
}
//设置取消类型 PTHREAD_CANCEL_DEFERRED
//接收到取消请求后,一直等待直到线程执行了下述函数之一后才采取行动
res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
if (res != 0)
{
perror("Thread Setcanceltype Failed!");
exit(EXIT_FAILURE);
}
printf("thread_function is running......\n");
for(i=0;i<10;i++)
{
printf("Thread is still running (%d) \n", i);
sleep(1);
}
pthread_exit(0);
}
run:
./a.out
thread_function is running......
Thread is still running (0)
Thread is still running (1)
Thread is still running (2)
Cancleing Thread...
Waiting For Thread To Finished...
Thread Canceled!