Mutual Exclusion with NON Busy Waiting

来源:互联网 发布:java jsonp跨域 编辑:程序博客网 时间:2024/05/16 23:45

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.  原来是编译器来实现的。而程序员不需要知道是怎么实现的。

 

 

 

原创粉丝点击