From 2ffbeae0238b1ccdae331f70a3c4e80099e40f53 Mon Sep 17 00:00:00 2001 From: pej97pfiw <1915225767@qq.com> Date: Wed, 13 Apr 2022 17:53:42 +0800 Subject: [PATCH] Add hellothread_producers_consumer --- hellothread_producers_consumer | 50 ++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 hellothread_producers_consumer diff --git a/hellothread_producers_consumer b/hellothread_producers_consumer new file mode 100644 index 0000000..4ffca8c --- /dev/null +++ b/hellothread_producers_consumer @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include +#include +int n=10, in=0,out=0,buffer[10]; +sem_t empty,full,mutex; +void* producer(void *arg){ + int tag= pthread_self()%100; + int nextPro; + srand(time(NULL)+tag); + while(1){ + nextPro = rand()%97; + sem_wait(&mutex); + 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); + sem_post(&mutex); + 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); + sem_init( &mutex, 0,1); + 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"); +} \ No newline at end of file