From 75b37f6eb8b6edc3693d98a28c8f92fc8e191fbf Mon Sep 17 00:00:00 2001 From: pfb6s459y <3522880783@qq.com> Date: Sun, 10 Apr 2022 18:16:17 +0800 Subject: [PATCH] ADD file via upload --- 3.2.txt | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 3.2.txt diff --git a/3.2.txt b/3.2.txt new file mode 100644 index 0000000..0348ee1 --- /dev/null +++ b/3.2.txt @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include +#include +int n=10, in=0,out=0,buffer[10]; +sem_t empty,full; +void* producer(void *arg){ + int tag= pthread_self()%100; + int nextPro; + srand(time(NULL)+tag); + while(1){ + nextPro = rand()%97; + sem_wait(&empty); + buffer[in] = nextPro; + printf("production:%d %d\n",nextPro,buffer[in]); +usleep(1000*1000/20); + in = (in+1)%n; + sem_post(&full); + usleep(1000*1000/2); + } +} +void* consumer(void *arg) { + int item; + while(1){ + sem_wait(&full); + item = buffer[out]; + sem_post(&empty); + printf("consume:%d\n",buffer[out]); + out = (out+1)%n; + usleep(1000*1000/10); + } +} +int main() { + pthread_t tid[7]; + //��ʼ��10�������� + sem_init( &empty, 0,10); + sem_init( &full, 0,0); + //pthread_create(&tid[0], NULL, producer, NULL); + for(int i=0;i<6;i++){ + 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"); +}