Mutual Exclusion with NON Busy Waiting

Sleep and Wakeup

 

The producer - Consumer problem

 

#define N 100                                        /* number of slots in the buffer */
int count = 0;                                       /* number of items in the buffer */

void producer(void)
{
     int item;

     while (TRUE){                                   /* repeat forever */
          item = produce_item();                     /* generate next item */
          if (count == N) sleep();                   /* if buffer is full, go to sleep */
          insert_item(item);                         /* put item in buffer */
          count = count + 1;                         /* increment count of items in buffer */
          if (count == 1) wakeup(consumer);          /* was buffer empty? */
     }
}


void consumer(void)
{
     int item;

     while (TRUE){                                   /* repeat forever */
          if (count == 0) sleep();                   /* if buffer is empty, got to sleep */
          item = remove_item();                      /* take item out of buffer */
          count = count  1;                         /* decrement count of items in
 buffer */
          if (count ==N  1) wakeup(producer);      /* was buffer full? */
          consume_item(item);                        /* print item */
     }
}

 

 

Semaphores

 

用数字记录 wakeup次数 为将来使用。

The normal way is to implement up and down as system calls, with the operating system briefly disabling all interrupts while it is testing the semaphore, updating it, and putting the process to sleep, if necessary. 通常的实现方式是 disable interrupt

If multiple CPUs are being used, each semaphore should be protected by a lock variable, with the TSL instruction used to make sure that only one CPU at a time examines the semaphore. 如果有多个cpu,就要使用TSL来防止多个cpu之间的竞争。注意 这里的TSL不是忙等。

 

使用Semaphore可以解决 producer-consumer 问题

 

 

 

Monitor

 

Monitors are a programming language construct, so the compiler knows they are special and can handle calls to monitor procedures differently from other procedure calls. Typically, when a process calls a monitor procedure, the first few instructions of the procedure will check to see if any other process is currently active within the monitor. If so, the calling process will be suspended until the other process has left the monitor. If no other process is using the monitor, the calling process may enter.

蛮奇怪的,这个过程怎么看上去像是busy wait

 

It is up to the compiler to implement the mutual exclusion on monitor entries, but a common way is to use a mutex or binary semaphore.  原来是编译器来实现的。而程序员不需要知道是怎么实现的。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值