本人設計了一個高效讀寫鎖,可實現多個線程讀一個線程寫的鎖,應該比Delphi自帶的讀寫鎖高效,本人沒有做對比測試。
本文的鎖不可以在一個線程裡重入,否則會鎖死,另外讀寫鎖最多支持65535個線程同時讀。
//HeZiHang@cnblogs //跨平台簡易高效鎖 unit uLocker; interface type //多讀單寫鎖 //1.寫的時候阻塞其他所有寫和讀 //2.讀的時候不阻塞其他讀,但阻塞所有寫,當阻塞了一個或以上的寫後,將阻塞所有後來新的讀 TMultiReadSingleWriteLocker = class FLocker: Integer; procedure LockRead; procedure UnLockRead; procedure LockWrite; procedure UnLockWrite; function TryLockRead:Boolean; function TryLockWrite:Boolean; constructor Create; end; TSimpleLocker=class FLocker:Integer; procedure Lock; procedure UnLock; function TryLock:Boolean; end; implementation uses System.SyncObjs, System.SysUtils; { TMultiReadSingleWriteLocker } procedure TMultiReadSingleWriteLocker.LockWrite; begin if TInterLocked.Add(FLocker, $10000) <> $10000 then begin while (TInterLocked.Add(FLocker, 0) and $FFFF) <> $10000 do Sleep(0); end; end; function TMultiReadSingleWriteLocker.TryLockRead: Boolean; begin Result:=TInterLocked.Increment(FLocker) and $FFFF0000 =0; if not Result then TInterLocked.Decrement(FLocker) end; function TMultiReadSingleWriteLocker.TryLockWrite: Boolean; begin Result:=TInterLocked.Add(FLocker, $10000) = $10000; end; procedure TMultiReadSingleWriteLocker.UnLockWrite; begin TInterLocked.Add(FLocker, -$10000); end; procedure TMultiReadSingleWriteLocker.UnLockRead; begin TInterLocked.Decrement(FLocker); end; constructor TMultiReadSingleWriteLocker.Create; begin FLocker:=0; end; procedure TMultiReadSingleWriteLocker.LockRead; begin if TInterLocked.Increment(FLocker) and $FFFF0000 <> 0 then begin while TInterLocked.Add(FLocker, 0) and $FFFF0000 <> 0 do Sleep(0); end; end; { TSimpleLocker } procedure TSimpleLocker.Lock; begin while TInterLocked.CompareExchange(FLocker, 1, 0)<>0 do Sleep(0); end; function TSimpleLocker.TryLock: Boolean; begin Result:= TInterLocked.CompareExchange(FLocker, 1, 0)=0; end; procedure TSimpleLocker.UnLock; begin TInterLocked.CompareExchange(FLocker, 0, 1); end; end.