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

拈花ヽ惹草 提交于 2019-12-01 16:37:37

问题


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.


回答1:


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




回答2:


Have a look at this tutorial. Threading the Delphi Way

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




回答3:


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.



来源:https://stackoverflow.com/questions/302583/how-can-i-implement-a-thread-safe-list-wrapper-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!