全文预览

《操作系统》课程设计-用多线程同步方法解决生产者-消费者问题

上传者:徐小白 |  格式:doc  |  页数:18 |  大小:0KB

文档介绍
ULL);Р?/*destroy the semaphores*/Р?sem_destroy(&producer_semaphore); Р?sem_destroy(&consumer_semaphore);Р?sem_destroy(&buffer_mutex);Р?fclose(fd);Р?return 0;Р}Рvoid *producer_thread(void *tid){Р?/*the thread can be canceled by other thread*/Р?pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);?Р?while(1){Р sem_wait(&producer_semaphore);Р srand((int)time(NULL)*(int)tid);Р sleep(rand()%2+1); /*one or two seconds to produce*/Р while((produce_pointer+1)%20==consume_pointer);Р sem_wait(&buffer_mutex);Р buffer[produce_pointer]=rand()%20+1;Р produce_pointer=(produce_pointer+1)%20;Р Р if(produce_pointer==0){ /*if buffer was filled to the 19th*/Р printf("producer:%d pointer_p:%2d produced:%2d\n",(int)tid,19,buffer[19]);Р fprintf(fd,"producer:%d pointer_p:%2d produced:%2d\n",(int)tid,19,buffer[19]);

收藏

分享

举报
下载此文档