Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2010-10

What are the issues involved in threads sharing variables?

3 messages · 3 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Frank Church

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.

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.

Frank Church ======================= http://devblog.brahmancreations.com

Reply by email

Andrew Brunner
to Frank Church
Frank Church wrote 6 lines
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"

Show quoted text 8 lines
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.

Reply by email

Brian Winfrey
to Andrew Brunner
Polling where the list size is highly dynamic you will need protect it.  I think FPC has thread safe list objects too.

Yes it does, Classes.TThreadList I think. I thought it was a conatiner for threads, but it is a safe list.

Reply by email