[fpc-pascal] Sharing dynamic arrays between threads

Wimpie Nortje wimpienortje at gmail.com
Fri Feb 25 14:02:13 CET 2011


Thanks for the resonse Jonas
>> Is it safe to create a dynamic array with setlength() in one thread and
>> free the array using finalize() in another thread?
>
> Normally, you should not call finalize() on dynamic arrays. When the
> last reference to a dynamic array goes out of scope, it is finalised
> automatically. It is safe when this happens in a different thread than
> the one in which it was created.

I have a producer thread that allocates memory for a record using new().
This record also contains a dynamic array, which is allocated with
setlength(). The record address is then put in a TThreadList.

The consumer thread gets the record address from the TThreadlist and
processes the data. The memory must then be free'd, in the consumer thread.

Initially I only disposed the record. This lead to lots of memory leaks.
Then I set dynarray:= nil before disposing the record. Less mem leaks,
but still a lot.
Then I started to finalize the dynamic array before disposing the
record. A huge improvement but still some leaks.

I get the feeling the arrays are sometimes not free'd but I don't
understand why.



More information about the fpc-pascal mailing list