#1 2024-09-06 11:43:52

squirrel
Member
Registered: 2015-08-13
Posts: 155

How to make IList threadsafe

Should the .Safe lock be used before/after all Add/Delete/Indexof/Pop methods to make it threadsafe, or is it already used by some of these functions?  O no, do I need to add read  locks around all the .Count functions too?

Would it be possible to make a fully threadsafe descendant of IList?

Last edited by squirrel (2024-09-06 13:26:56)

Offline

#2 2024-09-06 16:02:08

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,656
Website

Re: How to make IList threadsafe

Once you use indexes between method calls, it won't be thread safe.
The index may have changed in-between.

So you need to call Safe.Lock/UnLock properly, or even in R/W mode.

A full thread-safe descendant of IList won't be really thread-safe.
IKeyValue<> on the other hand has most of its methods thread-safe by default - at least all methods not relying to indexes.

Offline

#3 2024-09-06 18:08:19

squirrel
Member
Registered: 2015-08-13
Posts: 155

Re: How to make IList threadsafe

Thanks @ab.  I’ve done the whole lock/unlock thing everytime any of my code touches the IList, which obviously leads directly to copy/paste issues, and unreadable code.  I guess the only sensible way of using it then would be if I define a class which has the ilist as a property and custom add/delete/count/index/pop functions that lock/unlock as needed.

Offline

#4 2024-09-09 09:32:14

squirrel
Member
Registered: 2015-08-13
Posts: 155

Re: How to make IList threadsafe

ab wrote:

A full thread-safe descendant of IList won't be really thread-safe.

This seems a bit contradictory, is there something in the way that the locks are implimented that makes it impossible to make IList threadsafe?

Would something like this be safe where each function does a lock, calls the underlying function on IList and then unlock?

  TSafeList<T> = class
    IItems: IList<T>;
  public
    ...
    function Add(const value: T; wasadded: PBoolean = nil): PtrInt;
    procedure AddFrom(const Another: IList<T>; Offset: PtrInt = 0; Limit: PtrInt = -1);
    function Count: Integer;
    ...
  end;
function TSafeList<T>.Add(const value: T; wasadded: PBoolean): PtrInt;
begin
  IItems.Safe.Lock;
  Result := IItems.Add(value, wasadded);
  IItems.Safe.UnLock;
end;

Offline

#5 2024-09-09 15:44:30

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,656
Website

Re: How to make IList threadsafe

Apart from an AddOne() or AddFrom() with no returned index value, I don't see many methods which could be thread-safe.

Even Count is not thread-safe.

Offline

Board footer

Powered by FluxBB