Synchronization/wait design for cross-thread event signaling (Obj-C)?

柔情痞子 提交于 2019-12-01 06:28:20

问题


In a Cocoa app, I have a setup like this:

  1. The main thread (M) can submit requests to a some background "producer" thread (B) to get some work done, say the result of a computation on item X.
  2. A different background thread (C) shortly thereafter might want the results of computing item X, and want those results synchronously.

Thread C could just re-do the work synchronously itself, but if thread B happens to be in the middle of computing item X already, I would like thread C to block and get the results from B. The results of the computation are findable on disk, so the data passing is not the issue.

What's the best way of blocking thread C until thread B is done with item X?

Note that there the items that B processes are arbitrary-- X is just one of many items in this example. I'd want to block until specifically item X is done.

So conceptually what I'd like is a way of thread B setting up some sort of flag when it starts saying "I'm working on X", and if C comes in and sees that flag, it waits for the flag to clear, and then gets the result.

Not sure if I can somehow shoehorn NSLocks into this role, or if there's a better primitive in the OS.

Any thoughts (or potential reframing of the problem) welcome! Thanks.


回答1:


If possible, use NSOperation. It has a -waitUntilFinished method to allow for synchronous computation. You'd just need some thread-safe storage mechanism to allow you to find the NSOperation for the item you're computing, if it already exists—say, an NSLock guarding an NSDictionary.




回答2:


An NSConditionLock could work nicely here. Perhaps a condition lock associated with each X. Initially condition "dormant" then set to "processing" by the background thread then set to "complete" when it is done. The calling thread could check for the "processing" condition and if it is set, wait until condition "complete" is reached.



来源:https://stackoverflow.com/questions/4099801/synchronization-wait-design-for-cross-thread-event-signaling-obj-c

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