开发者

Design pattern for multiple requestors where only one causes the resource to be fetched and all are notified when it's available?

开发者 https://www.devze.com 2023-02-10 15:10 出处:网络
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.

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 ove开发者_Go百科r 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?


Do you mean Mutex.TryLock()?

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消