读书人

linux下的c语言线程创建有关问题求解

发布时间: 2012-03-06 20:47:55 作者: rapoo

linux下的c语言线程创建问题,求解阿!
这是我的程序,执行后什么也没有。。。吾不解!

C/C++ code
#include<stdio.h>#include<pthread.h>void *thread1(void){    int i=0;    for(;i<10;i++)    {        printf("the 1st thread go %d\n",i);        sleep(1);    }}void *thread2(void){    int i=0;    for(;i<10;i++)    {        printf("the 2st thread go %d\n",i);        sleep(1);    }}void main(){    int a,b;    pthread_create(&a,NULL,(void *)thread1,NULL);    pthread_create(&b,NULL,(void *)thread2,NULL);}


[解决办法]
别让主线程退出太早~~
C/C++ code
int main(){    pthread_t a,b;    pthread_create(&a,NULL,(void *)thread1,NULL);    pthread_create(&b,NULL,(void *)thread2,NULL);        pthread_join(a,NULL);    pthread_join(b,NULL);     return 0;}
[解决办法]
在 main 里面调用一下 pthread_exit(), 会结束 main 函数所在的线程,不影响另外的线程
C/C++ code
void main(){    int a,b;    pthread_create(&a,NULL,(void *)thread1,NULL);    pthread_create(&b,NULL,(void *)thread2,NULL);    pthread_exit(NULL);} 

读书人网 >UNIXLINUX

热点推荐