luckyhoo
註冊時間: 2006-07-19 文章: 447
|
發表於: 星期一 十二月 15, 2008 9:43 am 文章主題: 主要行程與其產生的Thread之間運作的關係 |
|
|
由測試結果可以發現,主要行程與其產生Thread之間的運作是各自獨立的,但需要注意的是,當主要行程結束執行後,其產生的Thread也會跟著結束執行。
原始程式碼:
代碼: | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void * workthread(void *arg)
{
int Count=0;
for(;;Count++)
{
printf("thread echo %d times...\n", Count);
sleep(1);
}
return NULL;
}
void main(void)
{
int Count=0;
pthread_t theadid;
if(pthread_create(&theadid, NULL, workthread, NULL)!=0)
exit(-1);
for(;;Count++)
{
printf("main process echo %d times...\n", Count);
sleep(10);
}
} |
測試結果:
代碼: | [root@localhost ~]# gcc -pthread threadtest.c -o threadtest
[root@localhost ~]# ./threadtest
main process echo 0 times...
thread echo 0 times...
thread echo 1 times...
thread echo 2 times...
thread echo 3 times...
thread echo 4 times...
thread echo 5 times...
thread echo 6 times...
thread echo 7 times...
thread echo 8 times...
thread echo 9 times...
main process echo 1 times...
thread echo 10 times...
thread echo 11 times...
thread echo 12 times...
thread echo 13 times...
...... |
|
|