Chinaunix首页 | 论坛 | 博客
  • 博客访问: 317884
  • 博文数量: 28
  • 博客积分: 2156
  • 博客等级: 大尉
  • 技术积分: 232
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-02 15:31
文章分类

全部博文(28)

文章存档

2011年(7)

2010年(21)

分类: LINUX

2010-07-01 11:48:42

今天学习多线程的第二个例子是取消线程示例,在此程序中,主线程使用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.


===

阅读(1019) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~