2012-04-11 85 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共享資源的各種線程之間的訪問)。