From ec3247c0b187d3d974a8ecf9040fb943d15e456d Mon Sep 17 00:00:00 2001 From: pzu4aoly2 Date: Sat, 16 Apr 2022 18:24:27 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=20=E5=AE=9E=E9=AA=8C2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 实验2.1 | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/实验2.1 b/实验2.1 index 2f034a5..bf3a114 100644 --- a/实验2.1 +++ b/实验2.1 @@ -4,28 +4,28 @@ #include #include #include -int n=10, in=0,out=0,buffer[10]; -sem_t empty,full; +int n=10, in=0,out=0,buffer[10];//定义变量并创建数组。 +sem_t empty,full;//定义信号量 void* producer(void *arg){ - int tag= pthread_self()%100; + int tag= pthread_self()%100;//线程信号 int nextPro; - srand(time(NULL)+tag); + srand(time(NULL)+tag);//随机数种子 while(1){ nextPro = rand()%97; - sem_wait(&empty); + sem_wait(&empty);//empty–1 buffer[in] = nextPro; printf("production:%d %d\n",nextPro,buffer[in]); usleep(1000*1000/20); in = (in+1)%n; - sem_post(&full); + sem_post(&full);//full+1 usleep(1000*1000/2); } } void* consumer(void *arg) { int item; while(1){ - sem_wait(&full); + sem_wait(&fullfull item = buffer[out]; sem_post(&empty); printf("consume:%d\n",buffer[out]); @@ -35,12 +35,11 @@ void* consumer(void *arg) { } int main() { pthread_t tid[7]; - //初始有10个缓冲区 sem_init( &empty, 0,10); - sem_init( &full, 0,0); + sem_init( &full, 0,0);//初始化信号量 for(int i=0;i<6;i++) - pthread_create(&tid[i], NULL, producer, NULL); - pthread_create(&tid[6], NULL, consumer, NULL); + pthread_create(&tid[i], NULL, producer, NULL);//创建生产者 + pthread_create(&tid[6], NULL, consumer, NULL);//创建消费者 for(int i = 0; i<7; i++) pthread_join(tid[i], NULL); printf("main is over\n"); -- 2.34.1 From e4d3a41e12c59f2723bc0823dec4b77570cf0039 Mon Sep 17 00:00:00 2001 From: pzu4aoly2 Date: Sat, 16 Apr 2022 18:26:09 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=20=E5=AE=9E=E9=AA=8C2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 实验2.1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/实验2.1 b/实验2.1 index bf3a114..6d7c600 100644 --- a/实验2.1 +++ b/实验2.1 @@ -25,9 +25,9 @@ void* producer(void *arg){ void* consumer(void *arg) { int item; while(1){ - sem_wait(&fullfull + sem_wait(&full)//full–1 item = buffer[out]; - sem_post(&empty); + sem_post(&empty);//empty+1 printf("consume:%d\n",buffer[out]); out = (out+1)%n; usleep(1000*1000/10); @@ -41,6 +41,6 @@ int main() { pthread_create(&tid[i], NULL, producer, NULL);//创建生产者 pthread_create(&tid[6], NULL, consumer, NULL);//创建消费者 for(int i = 0; i<7; i++) - pthread_join(tid[i], NULL); + pthread_join(tid[i], NULL);//等待线程结束 printf("main is over\n"); } \ No newline at end of file -- 2.34.1