Chinaunix首页 | 论坛 | 博客
  • 博客访问: 808436
  • 博文数量: 489
  • 博客积分: 475
  • 博客等级: 下士
  • 技术积分: 3087
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 16:28
文章分类

全部博文(489)

文章存档

2013年(7)

2012年(301)

2011年(181)

分类:

2011-12-22 20:50:55

原文地址:线程终止 作者:luozhiyong131

 

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *thread(void *str)
{
    int i;
    for (i = 0; i < 3; ++i)
    {
        sleep(2);
        printf( "This in the thread : %dn" , i );
    }
    return NULL;
}

int main()
{
    pthread_t pth;
    int i;

    /*创建线程并执行线程执行函数*/
    int ret = pthread_create(&pth, NULL, thread, NULL);
    
    printf("The main process will be to run,but will be blocked soonn");
    
    /*阻塞等待线程退出*/
    pthread_join(pth, NULL);

    printf("thread was exitn");
    for (i = 0; i < 3; ++i)
    {
        sleep(1);
        printf( "This in the main : %dn" , i );
    }
    
    return 0;
}


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

void mythread()
{
    int i;
    for(i=0;i<3;i++)
    {
        printf("this is a pthread:n");
    }
    pthread_exit("thank you for the cpu timen");
}

int main()
{
    pthread_t id;
    int i,ret;
    void *thread_result;
    ret=pthread_create(&id,NULL,(void *)mythread,NULL);
    if(ret!=0)
    {
        printf("create pthread errorn");
        exit(1);
    }
    for(i=0;i<3;i++)
    {
        printf("this is the main:n");
    }
    pthread_join(id,&thread_result);
    printf("thread joined, it returned:%s",(char *)thread_result);
    return 0;    
}


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

void mythread()
{
    int i,ret;
    
    ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
    if(ret!=0)
    {
        printf("thread pthread_setcancelstate failedn");
        exit(1);
    }
    
    ret = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
    if(ret!=0)
    {
        printf("thread pthread_setcanceltype failedn");
        exit(1);
    }
    
    for(i=0;i<10;i++)
    {
        printf("this is a pthread:n");
        sleep(1);
    }
    pthread_exit("thank you for the cpu timen");
}

int main()
{
    pthread_t id;
    int ret;
    void *thread_result;
    ret=pthread_create(&id,NULL,(void *)mythread,NULL);
    if(ret!=0)
    {
        printf("create pthread errorn");
        exit(1);
    }
    sleep(3);
    printf("cancleing thread....n");
    ret = pthread_cancel(id);
    if(ret!=0)
    {
        printf("thread pthread_cancel failedn");
        exit(1);
    }    
    sleep(2);
    pthread_join(id,&thread_result);
    printf("thread joined, it returned:%s",(char *)thread_result);
    return 0;    
}


阅读(310) | 评论(0) | 转发(0) |
0

上一篇:线程属性(线程分离)

下一篇:消息列队

给主人留下些什么吧!~~