Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7650004
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: 嵌入式

2010-12-11 09:08:00

 

#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;    
}


阅读(1444) | 评论(0) | 转发(3) |
0

上一篇:线程创建

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

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