Hello all,
I have enhanced my RWLock algorithm, now please
follow with me..
In my previous version the RLock() method was like this:
==
procedure TRWLOCK.RLock;
var count:ulong;
begin
repeat
count:=LockedExchangeAdd(FCount2^,2);
if (count mod 2) = 0
then break
else LockedExchangeAdd(FCount2^,-2);
if mysleep=1 then sleep(random(2))
else sleep(0);
until false;
end;
==
and the WLock() method was like this:
==
procedure TRWLOCK.WLock;
var count:ulong;
begin
while not CAS(FCount1^,0,1)
do
begin
if mysleep=1 then sleep(random(2))
else sleep(0);
end;
LockedExchangeAdd(FCount2^,1);
while (FCount2^ <>1)
do
begin
if mysleep=1 then sleep(random(2))
else sleep(0);
end;
end;
==
So what was the problem then ? the problem is when the
WLock() method will execute the following part of the code:
--
while (FCount2^ <>1)
do
begin
if mysleep=1 then sleep(random(2))
else sleep(0);
end;
end;
--
It can starve , like a deadlock, cause the RLock() is spinning and incrementing and decrementing by 2 the FCount2^, so to solve
this problem i have to stop the readers that enter the RLock() method when the writer have incremented FCount2^ by 1, and this is done by
my new algorithm, hwew is the new RWLock() method:
==
procedure TRWLOCK.RLock;
var count,count1:int;
begin
repeat
count:=LockedExchangeAdd(FCount2^,2);
if (count mod 2) = 0
then break
else
begin
count:= LockedExchangeAdd(FCount2^,-2);
while (FCount2^ and (not(not 1))) = 1
do if mysleep=1 then sleep(random(2))
else sleep(0);
end;
if mysleep=1 then sleep(random(2))
else sleep(0);
until false;
end;
--
So as you have noticed there is a
FCount2^ and (not(not 1))) = 1
to test on the first bit , if it is equal
to 1 that means that the writer have entered and incremented
FCount2^ by 1, hence the readers will not spin by incrementing
and decrementing FCount2^ by 2 , but they will spin on a sleep(0)
until FCount2^ will not equal to 1, so my new algorithm is efficient now
and it is 2X faster than the lockfree TOmniMREW that you will
find on the Omnithread library.
You can download my new RWLock versoin 1.1 with my new algorithm
from:
http://pages.videotron.com/aminer/Thank you,
Amine Moulay Ramdane.