Chinaunix首页 | 论坛 | 博客
  • 博客访问: 630696
  • 博文数量: 1008
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 5175
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-31 09:44
文章分类
文章存档

2012年(1008)

我的朋友

分类:

2012-08-01 11:35:08

原文地址:线程终止 作者: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;    
}


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

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

下一篇:线程创建

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