4、;}printf("thread2:主函數(shù)在等我完成任務(wù)嗎?");pthread_exit(NULL);}voidthread_create(void){inttemp;memset(&thread,0,sizeof(thread));//comment1/*創(chuàng)建線程*/if((temp=pthread_create(&thread[0],NULL,thread1,NULL))!=0)//comment2printf("線程1創(chuàng)建失敗!");elseprintf("線程1被創(chuàng)建");if((te
5、mp=pthread_create(&thread[1],NULL,thread2,NULL))!=0)//comment3printf("線程2創(chuàng)建失敗");elseprintf("線程2被創(chuàng)建");}voidthread_wait(void){/*等待線程結(jié)束*/if(thread[0]!=0){//comment4pthread_join(thread[0],NULL);printf("線程1已經(jīng)結(jié)束");}if(thread[1]!=0){//comment5pthread_join(thr
6、ead[1],NULL);printf("線程2已經(jīng)結(jié)束");}}intmain(){/*用默認(rèn)屬性初始化互斥鎖*/pthread_mutex_init(&mut,NULL);printf("我是主函數(shù)哦,我正在創(chuàng)建線程,呵呵");thread_create();printf("我是主函數(shù)哦,我正在等待線程完成任務(wù)阿,呵呵");thread_wait();return0;}下面我們先來編譯、執(zhí)行一下引文:falcon@falcon:~/program/c/code/ftp$gcc-lpthrea
7、d-othread_examplethread_example.cfalcon@falcon:~/program/c/code/ftp$./thread_example我是主函數(shù)哦,我正在創(chuàng)建線程,呵呵線程1被創(chuàng)建線程2被創(chuàng)建我是主函數(shù)哦,我正在等待線程完成任務(wù)阿,呵呵thread1:I'mthread1thread1:number=0thread2:I'mthread2thread2:number=1thread1:number=2thread2:number=3thread1:number=4threa
8、d2:number=5thread1:number=6thread1:number=7thread2:number=8thread1:number=9thread2:number=10thread1:主函數(shù)在等我完成任務(wù)嗎?線程1已經(jīng)結(jié)束thread2:主函數(shù)在等我完成任務(wù)嗎?線程2已經(jīng)結(jié)束實(shí)例代碼里頭的注釋應(yīng)該比較清楚了吧,下面我把網(wǎng)路上介紹上面涉及到的幾個(gè)函數(shù)和變量給引用過來。引文:線程相關(guān)操作一pthrea