1. 程式人生 > >多線程同步精要

多線程同步精要

ould tro 另一個 進程 rec tween ide 銷毀 思考

單機並發編程有兩種基本模型:"消息傳遞"和"共享內存";分布式系統運行在多臺機器上,只有一種實用模型:"消息傳遞"。

單機上多進程並發可以照搬"消息傳遞",多線程編程用"消息傳遞"更容易保證程序的正確性。

多線程同步有很多種方式:互斥量、條件變量、信號量、讀寫鎖等。盡量不要用信號量和讀寫鎖

Don’t use a semaphore where a mutex would suffice. A semaphore is a generic synchronization primitive originally described by Dijkstra that can be used to effect a wide range of behavior. It may be tempting to use semaphores in lieu of mutexes to protect critical sections, but there is an important difference between the two constructs: unlike a semaphore, a mutex has a notion of ownership

—the lock is either owned or not, and if it is owned, it has a known owner. By contrast, a semaphore (and its kin, the condition variable) has no notion of ownership: when sleeping on a semaphore, one has no way of knowing which thread one is blocking upon.(引自《Real-World Concurrency》http://queue.acm.org/detail.cfm?id=1454462)

信號量的另一個問題是:它有自己的計數值,通常我們自己的數據結構也有長度值,這就造成了同樣的信息存了兩份,這就需要時刻保持一致,增加了程序員的負擔和出錯的可能。

mutex和condition variable是用的最多的,用他們兩個足以應對大多數的使用場景。

互斥量mutex

原則:

1.利用RAII自動創建、銷毀、加鎖、解鎖,不手動調用lock() unlock()函數。

2.只用在線程同步中,不用跨進程的mutex。

3.首選非遞歸mutex(不可重入mutex)。附:windows的CRITICAL_SECTION是可重入的,linux下mutex默認是不可重入的。不可重入mutex的優點是:在同一個線程裏多次對non-recursive mutex加鎖會立刻導致死鎖,這能夠幫助我們思考代碼對鎖的期求,並且及早(在編碼階段)發現問題。

多線程同步精要