【问题标题】:Result of algorithm in reverse, Producer-Consumer solution using Semaphores反向算法的结果,使用信号量的生产者-消费者解决方案
【发布时间】:2014-11-04 01:08:33
【问题描述】:

使用此信号量算法解决生产者-消费者问题,其中信号量按缓冲区大小递减,然后信号量减 1,表示临界区。

如果这些操作是背靠背连续发生的,为什么减 1(互斥体)然后减小缓冲区大小是不正确的?

我知道生产者和消费者会同时进入休眠状态,造成死锁,但为什么这个小开关会导致整个算法失败?

BufferSize = 3;

semaphore mutex = 1;              // Controls access to critical section
semaphore empty = BufferSize;     // counts number of empty buffer slots
semaphore full = 0;               // counts number of full buffer slots

Producer()
{
  int widget;

  while (TRUE) {                  // loop forever
    make_new(widget);             // create a new widget to put in the buffer
    down(&empty);                 // decrement the empty semaphore
    down(&mutex);                 // enter critical section
    put_item(widget);             // put widget in buffer
    up(&mutex);                   // leave critical section
    up(&full);                    // increment the full semaphore
  }
}

Consumer()
{
  int widget;

  while (TRUE) {                  // loop forever
    down(&full);                  // decrement the full semaphore
    down(&mutex);                 // enter critical section
    remove_item(widget);          // take a widget from the buffer
    up(&mutex);                   // leave critical section
    up(&empty);                   // increment the empty semaphore
    consume_item(widget);         // consume the item
  }
}

代码来源:Resource

【问题讨论】:

    标签: c algorithm semaphore


    【解决方案1】:

    这是不正确的,因为如果生产者通过 wait(mutex) 进入代码部分,但随后发现没有空块,所以它必须等待空信号量。同时,当消费者尝试进入时,它必须等待互斥锁,因为生产者已锁定互斥锁。因此存在死锁,因为生产者正在等待消费者消费,而消费者正在等待生产者发出信号(互斥锁) 对于互斥量和信号量的原始安排,情况并非如此,其中生产者或消费者仅在其减少信号量值时才允许等待互斥量。因此没有死锁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多