Synchronization/wait design for cross-thread event signaling (Obj-C)?
In a Cocoa app, I have a setup like this:
- 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.
- 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.
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
.
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.
精彩评论