Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1)Lock-Free
- 2)Wait-Free
- 3)Wait-Freedom
- function TgjRingBuffer.InsertLeft(const link: pointer): integer;
- var
- AtStartReference: cardinal;
- CPUTimeStamp : int64;
- CurrentLeft : pointer;
- CurrentReference: cardinal;
- NewLeft : PReferencedPtr;
- Reference : cardinal;
- label
- TryAgain;
- begin
- Reference := GetThreadId + 1; //Reference.bit0 := 1
- with rbRingBuffer^ do begin
- TryAgain:
- //Set Left.Reference with respect to all other cores :)
- CPUTimeStamp := GetCPUTimeStamp + LoopTicks;
- AtStartReference := Left.Reference OR 1; //Reference.bit0 := 1
- repeat
- CurrentReference := Left.Reference;
- until (CurrentReference AND 1 = 0)or (GetCPUTimeStamp - CPUTimeStamp > 0);
- //No threads present in ring buffer or current thread timeout
- if ((CurrentReference AND 1 <> 0) and (AtStartReference <> CurrentReference)) or
- not CAS32(CurrentReference, Reference, Left.Reference) then
- goto TryAgain;
- //Calculate RingBuffer NewLeft address
- CurrentLeft := Left.Link;
- NewLeft := pointer(cardinal(CurrentLeft) - SizeOf(TReferencedPtr));
- if cardinal(NewLeft) < cardinal(@Buffer) then
- NewLeft := EndBuffer;
- //Calcolate distance
- result := integer(Right.Link) - Integer(NewLeft);
- //Check buffer full
- if result = 0 then //Clear Reference if task still own reference
- if CAS32(Reference, 0, Left.Reference) then
- Exit else
- goto TryAgain;
- //Set NewLeft.Reference
- NewLeft^.Reference := Reference;
- SFence;
- //Try to set link and try to exchange NewLeft and clear Reference if task own reference
- if (Reference <> Left.Reference) or
- not CAS64(NewLeft^.Link, Reference, link, Reference, NewLeft^) or
- not CAS64(CurrentLeft, Reference, NewLeft, 0, Left) then
- goto TryAgain;
- //Calcolate result
- if result < 0 then
- result := Length - integer(cardinal(not Result) div SizeOf(TReferencedPtr)) else
- result := cardinal(result) div SizeOf(TReferencedPtr);
- end; //with
- end; { TgjRingBuffer.InsertLeft }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement