如何在 Delphi 中实现线程安全列表包装器?
我有一个列表包装器,它维护两个 Tstringlists 和一个 TClassList
我需要它是线程安全的,这样:
- 不允许并发写入(应进入某种等待状态)
- 不允许边写边读(反之亦然)(应该进入某种等待状态)
- 允许并发读取
关于如何做到这一点有什么想法吗? 我的直觉告诉我,它需要的不仅仅是一个关键部分,也许是一个信号量或“使用计数器”,也许其中之一与 CS 结合使用。
我只是不太确定从哪里开始 - 从英语的整体方法到伪代码,再到 delphi 实现或外部链接,我将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该查看 sysutils.pas 中声明的 TMultiReadExclusiveWriteSynchronizer 类...
You should have a look at the TMultiReadExclusiveWriteSynchronizer class declared in sysutils.pas...
看看这个教程。
以 Delphi 方式进行线程
看看第 11 章,但都很好东西。
Have a look at this tutorial.
Threading the Delphi Way
Look at Chapter 11, but it's all good stuff.
你确实应该看看 TThreadList。
.Add、.Remove、.Clear 方法会自动为您锁定列表。 如果需要,您还可以根据需要锁定/解锁:
TMultiReadExclusiveWriteSynchronizer 是一个伟大的想法,但我不知道他们是否解决了所有错误。 它总是在负载下出现问题。
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:
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.