我正在尝试用信号量解决多个生产者/消费者问题。
我解决了一个特定情况下多个生产者/消费者的问题 - 当buffer
的大小为1.但是,我很难找到我应该对我的代码做什么修改来解决问题缓冲区的大小大于1,仍有许多生产者和消费者。
缓冲区大小= 1时的工作解决方案
当buffer
的大小为1时,这是我的工作解决方案的伪代码。(代码使用一个名为libIPC
的库,这个库不是很受欢迎,所以我提出伪代码)
共享内存是:
typedef struct {
int buffer;//the buffer size is 1,so it is only one integer
int nbconsumers;
//shared counter between all processes indicating the number of consumers that read the message
} t_segpart;
t_segpart *sp;
我使用3个信号量,如下所述:
sem_t* sem_produce ;
// semaphore blocking the producers when the buffer is full
sem_t* sem_consumer[NR] ;
// semaphore blocking the consumers when there is no message in the buffer
sem_t* mutex ;
// Mutual exclusion semaphore for protected access to nbconsumers
producer
代码:
while(1)
{
P(sem_producer);//producer demands a permission to write in the buffer
Produce the message in the buffer
for each consummer i
V(sem_consumer[i]);//Give access to consumers so that the can read the buffer
}
consumer
代码是:
while(1)
{
ind = index_consumer(id);
P(sem_consumer[ind]);//the receiver wants a permission to read the message
P(mutex);
read the buffer
sp->nbconsumer++;//upgrade nbconsummer
if(all consumers have read the message)
{
V(sem_produce);//Give access to producers so that they can produce a new message in the buffer
sp->nbconsumer = 0;// nobady has read yet the new buffer
}
V(mutex);
}
当缓冲区大小为1时,此解决方案适用于此特定情况。
你能否告诉我如何修改它以使其适用于更大尺寸的缓冲区?我应该介绍哪些信号量?我应该对共享内存进行任何更改吗?例如,我认为buffer
将不再是简单int variable
,而是array of int
。
当缓冲区大小大于1时,能否给出一个伪代码?