多个请求者的设计模式,其中只有一个请求者导致资源被获取,并且当资源可用时所有请求者都会收到通知?

发布于 2024-10-17 05:52:52 字数 227 浏览 1 评论 0原文

多个线程可以向资源请求但只有一个成功的设计模式是什么?当资源可用时,所有其他请求者都会收到通知。

例如,两个或多个线程请求通过网络获取的资源文件。第一个线程会阻塞其他两个线程。第一个线程生成单个请求,然后等待资源变得可用,就像其他两个等待线程一样。

当我说等待时,它们并不是真正等待阻塞,而是检查变量或其他东西,因为这已经是线程池的一部分,因此其他线程可以执行其他工作。

这种设计模式叫什么?

What would be a suitable design pattern where multiple threads could request from a resource, but only one of them succeeds. All the other requesters are notified when the resource is available.

For example, two or more threads requests a resource file which is obtained over the network. The first one in blocks the other two threads. The first thread generates a single request and then waits for the resource to become available just like the other two waiting threads.

When I say waiting, they don't really wait blocking, they check a variable or something because this is already part of a thread-pool so those other threads can do other work.

What is that design pattern called?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

哀由 2024-10-24 05:52:52

您的意思是 Mutex.TryLock() 吗?

免责声明:在 Windows/.NET 术语中;其他平台和语言中的名称和语法可能有所不同。

Do you mean Mutex.TryLock()?

Disclaimer: In Windows/.NET terminology; names and syntax may differ in other platforms and languages.

镜花水月 2024-10-24 05:52:52

您大致有三种选择:

  • 使用“futures”的想法 - 在 java 中,有一个接口 java.util.concurrent.Future,但这个想法很容易用其他语言表达 - 第一个线程创建一个 future 并将其放入全局映射,随后的线程拾取它并等待它被实现或在可以时检查它并在准备好时对其进行操作。
  • 使用 futures,但将第一个线程移交给另一个线程(来自池)来执行实际加载;这涉及更多线程,但使主线程的代码更简单,因为它们不必担心它们是否是第一个线程。
  • 将加载资源的使用放在回调中,由主线程注册,并由加载资源的线程调用。

我非常喜欢第二种选择,但选择实际上取决于您的特定要求。

You have roughly three choices:

  • Use the idea of 'futures' - in java, there's an interface java.util.concurrent.Future, but the idea is easily expressed in other languages - with the first thread creating a future and putting it in a global map, and later threads picking it up and either waiting for it to be realized or checking it when they can and acting on it when it's ready.
  • Use futures, but have the first thread hand off to another thread (from a pool) to do the actual loading; this involves more threads, but makes the code for the main threads simpler, because they don't have to worry about whether they're the first thread or not.
  • Put the use of the loaded resource in a callback, registered by the main threads, and called by the thread which loads the resource.

I quite like the second option, but the choice really depends on your particular requirements.

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