|
|
|
|
@ -1,2 +1,60 @@
|
|
|
|
|
# ThreadPrograming
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
#include <stdlib.h>//for exit()
|
|
|
|
|
#include <pthread.h>//for pthread()
|
|
|
|
|
#include <unistd.h> //for fork()and execl()
|
|
|
|
|
#include <sys/types.h>
|
|
|
|
|
#include <semaphore.h>//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");
|
|
|
|
|
}
|
|
|
|
|
|