全部博文(298)
分类: C/C++
2012-05-07 10:21:33
主线程睡眠和暂停
主要是测试主线程睡眠和主线程暂停是否对子线程有影响:都无影响
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秒的时候子线程结束,然后主线程永久暂停。