2012-04-11 66 views
13

以上两者有什么区别?互斥和同步的区别?

这个问题来到我的脑海,因为我发现,

  1. 监视器和锁提供互斥

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

是这是真的?

而且同时搜索,我发现这个article

任何澄清讨好。

回答

19

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

同步表示您将多个线程的访问同步/排序到共享资源。
考虑下面的例子:
如果你有两个线程,Thread 1 & Thread 2
Thread 1Thread 2并行执行,但是在Thread 1可以按其顺序执行一个语句A之前,Thread 2必须按其顺序执行语句B。你需要的是同步。信号量提供了这一点。您在Thread 1之前的语句A之前放置了semapohore,并且您在Thread 2之后的语句B之后发布了信号。
这可确保您需要的同步。

0

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

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

在上面的代码互斥变量提供互斥(只允许一个线程访问临界区),而充分和空变量被用于控制同步(以aribtrate共享资源的各种线程之间的访问)。