13
A
回答
19
相互排斥意味着只有一個線程應該能夠在任何給定的時間點訪問共享資源。這可以避免線程獲取資源之間的競爭條件。監視器和鎖提供了這樣做的功能。
同步表示您將多個線程的訪問同步/排序到共享資源。
考慮下面的例子:
如果你有兩個線程,Thread 1
& Thread 2
。
Thread 1
和Thread 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共享資源的各種線程之間的訪問)。
相關問題
- 1. 同步和互斥
- 2. 線程同步,互斥
- 3. 相互排斥和進程同步; C++
- 4. java方法同步和讀/寫互斥
- 5. 鎖定和同步使用互斥
- 6. 互斥鎖與pthread_join之間的區別
- 7. 單聲道嵌入:用於同步託管和本地互斥的互斥
- 8. 鎖,互斥和臨界區之間的區別
- 9. 使用互斥體的Pthread同步
- 10. 使用互斥鎖的pthread同步
- 11. Posix線程與互斥鎖的同步
- 12. 多個互斥體上的Windows同步
- 13. 線程同步 - 臨界區或互斥鎖?
- 14. 同步方法用作在Java互斥
- 15. 同步模式互斥保護塊
- 16. 線程和進程同步的信號量和互斥量
- 17. 內核編程中互斥和阻塞IO的區別?
- 18. 信號量和互斥量在實現中有什麼區別?
- 19. 互斥或不互斥互斥?
- 20. 同步屏幕輸出與互斥和pthread
- 21. 互斥使用等待,同步,中斷和通知
- 22. GCD臨界區/互斥
- 23. 共享互斥和互斥之間的區別(爲什麼都存在於C++ 11併發中)?
- 24. JMS/MQ和同步方法的區別
- 25. 同步之間的區別
- 26. C#中的互斥 - 來自代碼的非同步塊的同步
- 27. 互斥C#。如何系統識別互斥碼
- 28. 同步(this)和同步(objectReference)之間的區別
- 29. pthread_getspecific和互斥鎖
- 30. 互斥鎖和鎖