互斥和同步之间的区别?

时间:2012-04-11 06:24:27

标签: concurrency synchronization mutual-exclusion

上述两者有什么区别?

这个问题出现在我脑海中,因为我找到了

  1. 监视器和锁定提供互斥

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

  3. 这是真的吗?

    同时在搜索时我发现了article

    请澄清。

2 个答案:

答案 0 :(得分:22)

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

同步表示您将多个线程的访问权限同步/排序到共享资源。
考虑一下这个例子:
如果你有两个主题,Thread 1& Thread 2
Thread 1Thread 2并行执行,但在Thread 1可以执行之前,在其序列中声明AThread 2必须执行语句{{} 1}}在它的序列中。你需要的是同步。信号量提供了这一点。您在B中的语句A之前等待semapohore等待,并在Thread 1中的语句B之后发布到信号量。
这可确保您需要的同步。

答案 1 :(得分:0)

理解差异的最好方法是借助一个例子.Below是通过信号量解决经典生产者消费者问题的程序。为了提供互斥,我们通常使用二进制信号量或互斥量并提供我们使用的同步计算信号量。

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
  }
}

在上面的代码中,互斥变量提供互斥(只允许一个线程访问临界区),而完全变量和空变量用于同步(以便在各种线程之间实现共享资源的访问)。