如何在 Delphi 中实现线程安全列表包装器?

发布于 2024-07-08 11:30:13 字数 321 浏览 10 评论 0原文

我有一个列表包装器,它维护两个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

洛阳烟雨空心柳 2024-07-15 11:30:13

您应该查看 sysutils.pas 中声明的 TMultiReadExclusiveWriteSynchronizer 类...

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

隔岸观火 2024-07-15 11:30:13

看看这个教程。
以 Delphi 方式进行线程

看看第 11 章,但都很好东西。

Have a look at this tutorial.
Threading the Delphi Way

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

烂柯人 2024-07-15 11:30:13

你确实应该看看 TThreadList。

.Add、.Remove、.Clear 方法会自动为您锁定列表。 如果需要,您还可以根据需要锁定/解锁:

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

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文