From 76c7704d258e4338330049cf7b15aafdc0c71b2f Mon Sep 17 00:00:00 2001 From: przpe8i37 <2650404928@qq.com> Date: Tue, 5 Apr 2022 22:21:14 +0800 Subject: [PATCH] Update README.md --- README.md | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/README.md b/README.md index d2a28e3..5ff9643 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,60 @@ # ThreadPrograming +#include +#include //for exit() +#include //for pthread() +#include //for fork()and execl() +#include +#include //for sem_wait()and sem_post() +int n=10,in=0,out=0,buffer[10]; //global variables:buffer sem_t defines signal and two signal inited in main +//n用作取模,in和out分别当作生产者的放和消费者的取,buffer[10]代表十个缓冲区,可同时读和写 +sem_t empty,full; //当库存为空时,消费者不再拿。当库存为满时,生产者不再生产。 + +void* producer(void*arg) +{ + int tag=pthread_self()%100; //线程id的模,可重复 + int nextPro; //用作输出当前线程产品名 + srand(time(NULL)+tag); //pthread_self(): thread number Srand: rand seed; + // one producer produces constantly + while(1) + { + nextPro=rand()%97; + sem_wait(&empty); + buffer[in]=nextPro; + printf("production:%d %d\n",nextPro,buffer[in]); //buffer[in]可能在多线程中发生冲突而改变 + usleep(1000*1000/20); //sleep: unit is weimiao; 1 seconds = 1000*1000 weimiao,except 20 equal to 0.05 seconds; + in=(in+1)%n; + sem_post(&full); //wait and signal of signmount + usleep(1000*1000/2); + } +} +//consumer process +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/2); + } +} + +int main() +{ + pthread_t tid[2]; + //初始有10个缓冲区 + //线程号数组:根据需要,有多少线程,就定位多大 + sem_init(&empty,0,10); //整形信号量初始化函数:第3个参数表示信号量的初始值,第2个参数可暂时不管 + sem_init(&full,0,0); + pthread_create(&tid[0],NULL,producer,NULL); //create thread + pthread_create(&tid[1],NULL,consumer,NULL); + for(int i=0;i<2;i++) + { + pthread_join(tid[i],NULL); //等待所有线程结束,若不然,main结束后其他线程将被终止 + } + printf("main is over\n"); +}