【问题标题】:Difference between mutual exclusion and synchronization?互斥和同步的区别?
【发布时间】:2012-04-23 11:05:15
【问题描述】:

以上两者有什么区别?

我想到了这个问题,因为我发现

  1. 监视器和锁提供互斥

  2. 信号量和条件变量提供同步

这是真的吗?

在搜索时我也发现了这个article

请澄清。

【问题讨论】:

    标签: concurrency synchronization mutual-exclusion


    【解决方案1】:

    互斥意味着在任何给定时间点都应该只有一个线程能够访问共享资源。这避免了获取资源的线程之间的竞争条件。监视器和锁提供了这样做的功能。

    同步意味着您同步/排序多个线程对共享资源的访问。
    考虑这个例子:
    如果您有两个线程,Thread 1 & Thread 2
    Thread 1Thread 2 并行执行,但在 Thread 1 可以执行之前说语句 A 在其顺序中是必须的 @987654327 @ 应该按其顺序执行语句 B。您需要的是同步。信号量提供了这一点。您在Thread 1 中的语句A 之前放置了一个信号量等待,然后在Thread 2 中的语句B 之后发布到信号量。
    这确保了您需要的同步。

    【讨论】:

      【解决方案2】:

      理解差异的最佳方法是借助示例。以下是通过信号量解决经典生产者消费者问题的程序。为了提供互斥,我们通常使用二进制信号量或互斥体并提供我们使用的同步计数信号量。

      BufferSize = 3;
      
      semaphore mutex = 1;              // used for mutual exclusion
      semaphore empty = BufferSize;     // used for synchronization
      semaphore full = 0;               // used for synchronization
      
      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
           consume_item(widget);         // consume the item
        }
      }
      

      在上面的代码中,mutex 变量提供了互斥(只允许一个线程访问临界区),而 full 和 empty 变量用于同步(在各个线程之间分配共享资源的访问)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-28
        • 1970-01-01
        • 1970-01-01
        • 2011-06-10
        • 2012-03-12
        • 2011-04-13
        • 2010-10-22
        相关资源
        最近更新 更多