生产者 - 消费者生产者创建2个元素POSIX信号量

时间:2016-12-03 17:13:26

标签: c++ c posix semaphore producer-consumer

3消费者2生产者。读写一个缓冲区。 生产者A将1个元素推送到缓冲区(长度为N),生产者B将2个元素推送到缓冲区。没有活跃的等待。我无法使用System V信号量。

制作人A的示例代码:

void producerA(){
  while(1){
    sem_wait(full);
    sem_wait(mutex);

    Data * newData = (Data*) malloc(sizeof(Data));
    newData->val = generateRandomletter();
    newData->A = false;
    newData->B = false;
    newData->C = false;

    *((Data*) mem+tail) = *newData;

    ++elements;
    tail = (tail + 1) % N;

    sem_post(mutex); 
    sem_post(empty);
  }
}

消费者看起来很相似,除了他们阅读或消费但这无关紧要。 我对制作人B遇到了很多麻烦。显然我不能做像

这样的事情
sem_wait(full); sem_wait(full);

我还尝试为生产者B设置一个不同的信号量,这个信号量会在第一次缓冲区中有2个或更多的空闲点时被提升。但这并没有成功,因为我仍然需要适当降低和增加信号量fullempty

我可以在哪些方面解决这个问题?

1 个答案:

答案 0 :(得分:1)

https://gist.github.com/RobPiwowarek/65cb9896c109699c70217ba014b9ed20 这将解决我遇到的整个问题。

TLDR: 我可以提供的最简单的同步是使用信号量emptywhile(1){ down(mutex); size = get size if (condition related to size based on what process this is) { do your job; updateSize(int diff); // this can up() specific semaphores // based on size // each process has his own semaphore up(mutex); } else { up(mutex); down(process's own semaphore); continue; } } 来表示我已经推送到缓冲区的元素数量。但是,如果我有一个创建2个元素的生产者,那么这种解决方案对POSIX信号量不起作用。

我的解决方案是一个不同的概念 流程概述归结为:

class FooConcrete {
    getImpl : () => number;

    constructor(getImpl: () => number) {
        this.getImpl = getImpl;
    }

    get() : number {
        return this.getImpl();
    }
}

我希望将来对某人有用。

相关问题