[fpc-pascal] What are the issues involved in threads sharing variables?
Andrew Brunner
andrew.t.brunner at gmail.com
Fri Oct 15 16:12:05 CEST 2010
On Fri, Oct 15, 2010 at 5:20 AM, Frank Church <vfclists at gmail.com> wrote:
>
> I am writing an app involving 2 threads, and a timer loop in the UI.
>
> The first thread monitors network events, logs them into a database, appends
> them to a list.
>
Any time I see append to a list I always think "RTLCriticalSection"
> The second thread monitors the list, checks the events and updates a data
> structure, which is used by a timer loop in the main application to update
> the UI.
>
> What are the issues involved in making sure that the 2 threads don't
> conflicted over access to the list?
> This is my first foray into using threads that share memory structures.
>
You have to protect the list from access by other threads. CritcialSection
is the only way
InitCriticalSection - Creates it
DoneCriticalSection - Frees it
EnterCriticalSection - Locks list
DoneCritiicalSection - Unlocks list
Example
EnterCriticalSection(FLock);
Try
FList.Add(EntryP);
Finally
LeaveCriticalSection(FLock);
end;
Polling where the list size is highly dynamic you will need protect
it. I think FPC has thread safe list objects too.
See the FPC rtl.pdf documentation on TThreadList
2.63.1
TThreadList
Description
TThreadList is a thread-safe Tlist (307) implementation. Unlike TList,
it can be accessed read-
write by multiple threads: the list implementation will take care of
locking the list when adding or
removing items from the list.
More information about the fpc-pascal
mailing list