今天学习多线程的第二个例子是取消线程示例,在此程序中,主线程使用pthread_cancel()函数来取消线程。由于子线程首先调用pthread_setcancelstate()函数设置了线程的取消状态为PTHREAD_CANCEL_DISABLE,因此,不可取消子线程,主线程处于等待状态,经过一段时间后,子线程调用pthread_setcancelstate()函数设置了线程的取消状态为PTHREAD_CANCEL_ENABLE,允许取消,从而使主线程能够取消子线程。
程序的源代码如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg);
int main(int argc, char *argv[])
{
int res;
pthread_t a_thread;
void *thread_result;
//create child thread
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread creation failed.");
exit(EXIT_FAILURE);
}
printf("Cancelling thread...\n");
//cancel child thread
res = pthread_cancel(a_thread);
if (res != 0)
{
perror("Thread cancelation failed.");
exit(EXIT_FAILURE);
}
printf("waiting for thread to finish...\n");
//wait child thread to finish
res = pthread_join(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed.");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
int i, res, j;
res = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
if(res != 0)
{
perror("Thread pthread_setcancelstate failed");
exit(EXIT_FAILURE);
}
printf("thread cancel type is disable, can't cancle this thread\n");
for(i = 0; i < 3; i++)
{
printf("Thread is running (%d)...\n", i);
}
res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if(res != 0)
{
perror("Thread pthread_setcancelstate failed.");
exit(EXIT_FAILURE);
}
else
printf("Now change the cancelstat to ENABLE.\n");
sleep(200);
pthread_exit(0);
}
|
编译运行
[root@xudonglee AdvanceLinux]# cc pthread_cancle.c -pthread [root@xudonglee AdvanceLinux]# ./a.out Cancelling thread... waiting for thread to finish... thread cancel type is disable, can't cancle this thread Thread is running (0)... Thread is running (1)... Thread is running (2)... Now change the cancelstat to ENABLE.
|
===
阅读(995) | 评论(0) | 转发(0) |