How can I implement a thread-safe list wrapper in Delphi?
Asked Answered
B

3

6

I have a list wrapper that maintains two Tstringlists and a TClassList

I need this to be thread safe, such that:

  • Concurrent writes are not allowed (wait state of some sort should be entered)
  • Reading while writing (or vice versa) is not allowed (wait state of some sort should be entered)
  • Concurrent reads are allowed

Any ideas on how I can do this? My instinct tells me it needs more than just a critical section, perhaps a semaphore or "usage counter", perhaps one of these in conjunction with a CS.

I'm just not quite sure where to start - anything from an overall approach in english to psuedo-code, to delphi implementation or external link would be much appreciated.

Belicia answered 19/11, 2008 at 16:54 Comment(0)
B
12

You should have a look at the TMultiReadExclusiveWriteSynchronizer class declared in sysutils.pas...

Burgett answered 19/11, 2008 at 17:1 Comment(4)
Probably the longest class name in the RTL :)Keegan
they could so easily have called it TMREWSAnnunciate
They could easily have called it TGreenIdea and conveyed as much information as TMREWS would. Don't be afraid of long identifier names.Branscum
@Annunciate It is called TMREWSyncCocotte
A
5

Have a look at this tutorial. Threading the Delphi Way

Look at Chapter 11, but it's all good stuff.

Annunciate answered 19/11, 2008 at 17:4 Comment(2)
Awesome Link. Could have used this when I was doing more in Delphi a few years ago!Swithin
The original link appears dead - I think it was the same as this article by Martin HarveyWeig
H
2

You really should look at TThreadList.

The methods .Add, .Remove, .Clear automatically lock the list for you. If needed, you can also lock/unlock as needed:

x.LockList; 
try 
  //do whatever
finally  
  x.Unlocklist; 
end;

TMultiReadExclusiveWriteSynchronizer is a grand idea but I don't know if they ever ironed all the bugs out. It has always had issues under load.

Holdup answered 1/12, 2008 at 3:1 Comment(2)
That is not what the OP is wanting, as LockList() locks the list for exclusive access - parallel read access is therefore impossible.Mehta
I was completely unaware that TThreadList even existed until now. I had been using TStringList objects with all sorts of CriticalSections in my code. This will make life much simpler!Rodger

© 2022 - 2024 — McMap. All rights reserved.