如何實現同時n個線程寫或讀同一個文件?
封裝一個靜態類(Lock),定義兩個鎖(靜態屬性,實際上為信號量),分別為 寫鎖(_m_WriteLock) 和讀鎖(_m_ReadLock):public static ReaderWriterLock _m_ReadLock = new ReaderWriterLock(); public static ReaderWriterLock _m_WriteLock = new ReaderWriterLock();當線程寫入時,同時鎖住 讀寫鎖:LjLock._m_WriteLock.AcquireWriterLock(10000);//寫資源鎖.數字為超時時間操作結束后 LjLock._m_WriteLock.ReleaseWriterLock();當讀操作時只鎖寫操作:LjLock._m_ReadLock.AcquireReaderLock(10000);//讀鎖LjLock._m_ReadLock.ReleaseReaderLock();即可。
記住:一定要在操作完后ReleaseReaderLock();或ReleaseWriterLock()進行釋放。