Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2372098
  • 博文数量: 298
  • 博客积分: 7876
  • 博客等级: 准将
  • 技术积分: 5500
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-23 13:39
文章存档

2013年(2)

2012年(142)

2011年(154)

分类: C/C++

2012-03-01 11:24:49

主线程睡眠和暂停

 

主要是测试主线程睡眠和主线程暂停是否对子线程有影响:都无影响

1.       主线程睡眠

#include

#include

#include

 

pthread_t ntid;

 

void

printids(const char *s)

{

    pid_t      pid;

    pthread_t  tid;

    pid = getpid();

    tid = pthread_self();

 

    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int) pid,

           (unsigned int)tid, (unsigned int)tid); 

 

}

 

void *

thr_fn(void *arg)

{

    printids("new thread :");

    sleep(2);

printf("thread over\n");

    return ((void *)0);

//  pthread_exit((void*)0);

 

}

 

int

main(void)

{

 

    int err;

    err = pthread_create(&ntid, NULL, thr_fn, NULL);

 

    if(err != 0)

 

    {

       printf("can't create new thread : %s\n",

                  strerror(err));

       exit(-1);

 

    }

 

    printids("nain thread: ");

    sleep(4);

printf("main over\n");

    return 0;

}

程序结果:

nain thread:  pid 2488 tid 3077744320 (0xb772a6c0)

new thread : pid 2488 tid 3077741424 (0xb7729b70)

thread over //等待两秒出现

main over//等待4秒出现

结果分析:

在主线程4秒睡眠中,子线程仍然在运行,主线程睡眠第2秒的时候子线程结束,再等待两秒,主线程结束。

 

2.       主线程暂停

 

#include

#include

#include

 

pthread_t ntid;

 

void

printids(const char *s)

{

    pid_t      pid;

    pthread_t  tid;

    pid = getpid();

    tid = pthread_self();

 

    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int) pid,

           (unsigned int)tid, (unsigned int)tid); 

 

}

 

void *

thr_fn(void *arg)

{

    printids("new thread :");

    sleep(2);

printf("thread over\n");

    return ((void *)0);

//  pthread_exit((void*)0);

 

}

 

int

main(void)

{

 

    int err;

    err = pthread_create(&ntid, NULL, thr_fn, NULL);

 

    if(err != 0)

 

    {

       printf("can't create new thread : %s\n",

                  strerror(err));

       exit(-1);

 

    }

 

    printids("nain thread: ");

    pause();

printf("main over\n");

    return 0;

}

程序结果

nain thread:  pid 2488 tid 3077744320 (0xb772a6c0)

new thread : pid 2488 tid 3077741424 (0xb7729b70)

thread over //等待两秒出现

永久等待

结果分析:

在主线程暂停的时候,子线程仍然在运行,主线程暂停到第2秒的时候子线程结束,然后主线程永久暂停。

 

 

 

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