标签:
本人设计了一个高效读写锁,可实现多个线程读一个线程写的锁,应该比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.
标签:
原文地址:http://www.cnblogs.com/hezihang/p/5347460.html