[fpc-devel] Safely shareable objects

Andrew Brunner andrew.t.brunner at gmail.com
Sat Jul 2 05:01:53 CEST 2011


> function TDLLItem.getNextItem():TDLLItem;
> begin
>  EnterCriticalSection(FOwner.FLock);
>  Try
>     Result:=FNext;
>  Finally
>    LeaveCriticalSection(FOwner.FLock);
>  end;
> end;

Thread1 code
...
   itm=List.First;
   while itm<>nil do begin
     itm.Process;
     itm=item.Next; // good
   end;
...

Thread2 code
...
  item=List.Any; // represents any Item in the List(could be result of
iterator function)
  if isItemToBeDeleted(Item) then
    List.Delete(Item);
...

Remember, First, Next, are getters with Locking CS.  And if the lock
is acquired for list iterations we're really going to not be able to
use the list for transactional systems, which would be one of the
primary reasons why developers would use threads in the first place.

The problem here is we are never really going to be able to create
"fast and efficient" code to make an object like this ptr list
completely thread-safe.  Meaning threading  concepts must be
understood before a user creates and uses a list.

But in the code above, at some point thread1 will encounter and error
because List.Delete freed the Item.  And even though Delete, and all
item Next,Prev getter/setters were fenced, the data will eventually be
corrupted for multi-threaded usage.



More information about the fpc-devel mailing list