是否可以用两个信号量来解决生产者-消费者问题?

问题描述 投票:0回答:1

这是使用3个信号量的解决方案。想知道是否有办法减少使用,如果没有,为什么不这样做?

   sem_t full; // # of filled slots
   sem_t empty; // # of empty slots
   sem_t mutex; // mutual exclusion

   sem_init(&full, 0, 0);
   sem_init(&empty, 0, N);
   sem_init(&mutex, 0, 1);

   Producer(){
      sem_down(empty);
      sem_down(&mutex);
      // fill a slot
      sem_up(&mutex);
      sem_up(full);
   }

   Consumer() {
      sem_down(full);
      sem_down(&mutex);
      // empty a slot
      sem_up(&mutex);
      sem_up(empty);
   }
c operating-system semaphore producer-consumer
1个回答
1
投票

避免互斥的唯一方法是,如果信号量内的所有操作都是原子操作(可能很少)。互斥锁可以确保危险位一次发生并且不会被中断。

想象一下,如果您有两个线程试图做彼此依赖的事情。

Thread 1:  Add 3 to the ordered list
Thread 2:  Add 4 to the ordered list
List:  { 1, 2, 5, 7}

线程2在插入自己的数字之前需要查看线程1在哪里粘贴他的数字。因此,我们使用互斥锁来确保一次只有一个线程尝试将其编号插入列表。

在您的示例(以及其他在线示例)中的编写方式可能会使人相信整个过程都必须位于互斥锁内。如果您这样做,一次只能有一个线程可以工作!实际上,您将执行不依赖于互斥锁以外但在信号量内的其他线程的工作(例如生成随机数),并且仅保护将数字插入列表中。

semaphore(x)
long_expensive_computation
mutex(y)
order_critical_stuff
release(y)
release(x)
© www.soinside.com 2019 - 2024. All rights reserved.