日期:2014-05-16  浏览次数:20592 次

这该死的程序,怎么老有个2??
C/C++ code

#include<stdio.h>
#include<pthread.h>

int num1=1,num2=2;
void * mythread(void * attr)        //没有加上void 的后果是非常严重的!!
{
    int * num=(int *)attr;
    printf("%d\n",*num);
}

int main(int agrc,char *argv[])
{
    pthread_t tid1,tid2;
    int status;
    status = pthread_create(&tid1,NULL,mythread,&num1);
    if(status){
        printf("create failed!");
        return -1;
    }
    
    status = pthread_create(&tid2,NULL,mythread,&num2);
    if(status){
        printf("create failed!");
        return -1;
    }
    

/*    status = pthread_join(tid1,NULL);
    if(status){
        printf("error1!");
        return -1;
    }*/
    
    status = pthread_join(tid1,NULL);
    if(status){
        printf("error2!\n");
        return -1;
    }

    return 0;
}



------解决方案--------------------
2就是你第二个线程打印出来的啊

线程的启动不是按照你的代码顺序启动的,这个是靠内核的调度。

如果你希望2在1后面打印,必须要用一些线程同步的技术