3、Out;}2.編譯并運(yùn)行編譯方法gccmain.cclac.c./a.out運(yùn)行結(jié)果遇到的問(wèn)題及解決方法(二)進(jìn)程的使用1.運(yùn)行以下程序#include#include#includeintmain(){inti;/*獲得當(dāng)前進(jìn)程和其父進(jìn)程的ID號(hào)*/for(i=0;i<3;i++){fork();printf("i=%d當(dāng)前進(jìn)程的ID號(hào)為:%d;父進(jìn)程ID為:%d",i,getpid(),getppid());}//sleep(2);return0;}2.給出結(jié)果并分析3.如果恢復(fù)sleep語(yǔ)句,得到什么結(jié)果1.運(yùn)行教材
4、thread.c,觀察結(jié)果并做簡(jiǎn)要分析2.線程互斥,運(yùn)行以下代碼,觀察結(jié)果并簡(jiǎn)要分析#include#include#include#includevoid*producter_f(void*arg);/*生產(chǎn)者*/void*consumer_f(void*arg);/*消費(fèi)者*/intbuffer_has_item=0;/*緩沖區(qū)計(jì)數(shù)值*/_mutex_tmutex;/*互斥區(qū)*/intrunning=1;/*線程運(yùn)行控制*/intmain(void){pthread_tconsumer_t;/*消費(fèi)者線程參數(shù)
5、*/pthread_tproducter_t;/*生產(chǎn)者線程參數(shù)*/pthread_mutex_init(&mutex,NULL);/*初始化互斥*/pthread_create(&producter_t,NULL,(void*)producter_f,NULL);/*建立生產(chǎn)者線程*/pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL);/*建立消費(fèi)者線程*/usleep(1);/*等待,線程創(chuàng)建完畢*/running=0;/*設(shè)置線程退出值*/pthread_join(consumer_t,NULL);/*等待消費(fèi)者線程退出*/
6、pthread_join(producter_t,NULL);/*等待生產(chǎn)者線程退出*/pthread_mutex_destroy(&mutex);/*銷毀互斥*/return0;}void*producter_f(void*arg)/*生產(chǎn)者線程程序*/{while(running)/*沒(méi)有設(shè)置退出值*/{pthread_mutex_lock(&mutex);/*進(jìn)入互斥區(qū)*/buffer_has_item++;/*增加計(jì)數(shù)值*/printf("生產(chǎn),總數(shù)量:%d",buffer_has_item);/*打印信息*/pthread_mutex_unlock(&mutex);/*離開(kāi)互
7、斥區(qū)*/}}void*consumer_f(void*arg)/*消費(fèi)者線程程序*/{while(running)/*沒(méi)有設(shè)置退出值*/{pthread_mutex_lock(&mutex);/*進(jìn)入互斥區(qū)*/buffer_has_item--;/*減小計(jì)數(shù)值*/printf("消費(fèi),總數(shù)量:%d",buffer_has_item);/*打印信息*/pthread_mutex_unlock(&mutex);/*離開(kāi)互