有多个进程:多个生产者进程和多个消费者进程共享一个初始为空、固定大小为n的缓存(缓冲区)。生产者的工作是制造数据,只有缓冲区没满时,生产者才能把消息放入到缓冲区,否则必须等待; 同时,只有缓冲区不空时,消费者才能从中取出消息,一次消费一段数据(即将其从缓存中移出),否则必须等待。由于缓冲区是临界资源,它只允许一个生产者放入消息,或者一个消费者从中取出消息,同时只允许一个生产者进行制造,多个生产者不能同时制造,也只允许一个消费之进行消费,多个消费者不能同时进行消费。
设置三个信号量:empty (以记录有多少空位)、full (以记录有多少满位)以及mutex
(二进制信号量或互斥信号量,以保护对缓冲插入与删除的操作)
当信号量empty为0的时候,此时有限缓存已满,生产者必须等待,当信号量full为0的时候,此时有限缓存为空,消费者无法进行消费,必须等待
信号量mutex使得各个线程之间互斥,每次只允许一个线程进入临界区,一旦有线程进入自己的临界区,其余线程必须等待
有限缓存区为循环队列,尾部插入新的产品,头部产品先被消耗
# include
# include
# include
# include
# include
# include
# include
# include
#define BUFFER_SIZE 5
typedef int buffer_item;
//semaphores
sem_t empty, full, mutex;
//buffer
buffer_item buffer[BUFFER_SIZE];
int in, out;
//存储数据的结构体
struct data {
int id;
int opTime;
int lastTime;
int productId;
};
//有限缓存插入--生产
int insert_item(buffer_item item) {
/* insert item into buffer */
buffer[out] = item;
out = (out + 1) % BUFFER_SIZE;
return 0;
}
//有限缓存删除--消费
int remove_item(buffer_item *item) {
/* remove an object from buffer and then place it in item */
*item = buffer[in];
in = (in + 1) % BUFFER_SIZE;
return 0;
}
//生产者
void *producer(void* param) {
int productId = ((struct data*)param)->productId;
int lastTime = ((struct data*)param)->lastTime;
int opTime = ((struct data*)param)->opTime;
int id = ((struct data*)param)->id;
free(param);
sleep(opTime);
sem_wait(&empty);
sem_wait(&mutex);
/* critical section */
//add a item
insert_item(productId);
sleep(lastTime);
printf("Thread %d: Producer produce %d\n", id, productId);
sem_post(&mutex);
sem_post(&full);
pthread_exit(0);
}
//消费者
void *consumer(void* param) {
int lastTime = ((struct data*)param)->lastTime;
int opTime = ((struct data*)param)->opTime;
int id = ((struct data*)param)->id;
free(param);
sleep(opTime);
sem_wait(&full);
sem_wait(&mutex);
/* critical section */
//remove a item
buffer_item item;
remove_item(&item);
sleep(lastTime);
printf("Thread %d: Consumer consume %d\n", id, item);
sem_post(&mutex);
sem_post(&empty);
pthread_exit(0);
}
int main() {
//pthread
pthread_t tid; // the thread identifier
pthread_attr_t attr; //set of thread attributes
/* get the default attributes */
pthread_attr_init(&attr);
//initial the semaphores
sem_init(&mutex, 0, 1);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
in = out = 0;
int id = 0;
while(scanf("%d", &id) != EOF) {
char role; //producer or consumer
int opTime; //operating time
int lastTime; //run time
int productId; //product id
scanf("%c%d%d", &role, &opTime, &lastTime);
struct data* d = (struct data*)malloc(sizeof(struct data));
d->id = id;
d->opTime = opTime;
d->lastTime = lastTime;
if(role == 'P') {
scanf("%d", &productId);
d->productId = productId;
pthread_create(&tid, &attr, producer, d);
}
else if(role == 'C')
pthread_create(&tid, &attr, consumer, d);
}
//释放信号量
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
测试数据:
1 C 3 5
2 P 4 5 1
3 C 5 2
4 C 6 5
5 P 7 3 2
6 P 8 4 3