码迷,mamicode.com
首页 > Windows程序 > 详细

Delphi 高效读写锁

时间:2016-04-02 14:50:48      阅读:781      评论:0      收藏:0      [点我收藏+]

标签:

本人设计了一个高效读写锁,可实现多个线程读一个线程写的锁,应该比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.

 

Delphi 高效读写锁

标签:

原文地址:http://www.cnblogs.com/hezihang/p/5347460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!