Delphi 高效读写锁
Posted 子航
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Delphi 高效读写锁相关的知识,希望对你有一定的参考价值。
本人设计了一个高效读写锁,可实现多个线程读一个线程写的锁,应该比Delphi自带的读写锁高效,本人没有做对比测试。
本文的锁不可以在一个线程里重入,否则会锁死,另外读写锁最多支持65535个线程同时读。
//[email protected] //跨平台简易高效锁 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.
以上是关于Delphi 高效读写锁的主要内容,如果未能解决你的问题,请参考以下文章
java中ReentrantReadWriteLock读写锁的使用
go语言学习笔记 — 进阶 — 并发编程(10):读写互斥锁(sync.RWMutex) —— 在读比写多的环境下,比互斥锁更高效