日期:2014-05-16 浏览次数:20988 次
#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);
}
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 函数所在的线程,不影响另外的线程
void main()
{
    int a,b;
    pthread_create(&a,NULL,(void *)thread1,NULL);
    pthread_create(&b,NULL,(void *)thread2,NULL);
    pthread_exit(NULL);
}