您的位置:首页 > 其它

取消一个线程

2012-02-25 23:36 148 查看
有时,我们想让一个线程可以要求另一个线程终止,就像给它发送一个信号一样。线程有方法可以做到这一点,与信号处理一样,线程可以被要求终止时改变其行为。

#include <pthread.h>

int pthread_cancel(pthread_t thread);

这个函数简单易懂,提供一个线程标识符,我们就可以发生请求来取消它。但在接收到取消请求的一端,事情会稍微复杂一点,不过也不是非常复杂。线程可以用pthread_setcancelstate设置自己的取消状态。

#include <pthread.h>

int pthread_setcancelstate(int state,int *oldstate);

第一个参数的取值可以是PTHREAD_CANCEL_ENABLE,这个值允许线程接收取消请求;或者是PTHREAD_CANCEL_DISABLE,它的作用是忽律取消请求。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_function(void *arg);

int main()
{
int res;
pthread_t a_thread;
void *thread_result;

res = pthread_create(&a_thread,NULL,thread_function,NULL);

if(res != 0)
{
perror("Thread creation failed");
exit(EXIT_FAILURE);
}

sleep(3);
printf("Canceling thread....\n");
res = pthread_cancel(a_thread);
if(res != 0)
{
perror("Thread cancelation failed");
exit(EXIT_FAILURE);
}

printf("Waiting for thread to finish...\n");
res = pthread_join(a_thread,&thread_result);
if(res != 0)
{
perror("Thread join failed");
exit(EXIT_FAILURE);
}
}

void *thread_function(void *arg)
{
int i,res;
res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
if(res != 0)
{
perror("Thread pthread_setcancelstate failed");
exit(EXIT_FAILURE);
}

res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);

if(res != 0)
{
perror("Thread pthread_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);
}


./thread7

thread_function is running

Thread is still running (0)...

Thread is still running(1)...

Thread is still running(2)...

Canceling thread...

Waiting for thread to finish
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thread function null join