Hi,
Is it safe to create a dynamic array with setlength() in one thread and free the array using finalize() in another thread?

Mailing lists / fpc-pascal / 2011-02
5 messages · 2 people ·
Reply by email Subscribe to this list Your subscription
Read-only archive. Use j and k to move between messages.
Hi,
Is it safe to create a dynamic array with setlength() in one thread and free the array using finalize() in another thread?
Wimpie Nortje wroteIs 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.
Jonas
Thanks for the resonse Jonas
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.
Calling dispose() on a record with a dynamic array field will free the array (and recursively finalize all its elements) as long as the pointer on which you call it is correctly typed in the source code. The fact that you still get memory leaks after everything you are doing suggests that something else is wrong in your program.
Jonas
Thank you.