Hi
I've seen a few examples of using delegate with multiple threads for async image loading with cocoa's URL loading system.
I think the process goes like below.
Thread 1 : give thread 2 an operation to perform, and a delegate which thread 2 will access upon completion.
Thread 2 : upon completing the operation, calls a predefined selector on the delegate passed by thread 1.
I'd like to implement similar feature(async processing with delegate) with my own classes. The below pseudo code is similar to the process outlined above, but i'd like to make it more detailed for the sake of discussion of thread safety.
Thread 1 :
[begin critical section]
set delegate so that thread 2 can access
[end critical section]
fire an operation
-(void) dealloc (of the delegate object's class)
{
[begin critical section]
set delegate to null
[end critical section]
}
Thread 2 :
actually works on operation
- upon completion.. [begin critical section]
get delegate
[delegate performSelectorOnMainThread @someSelector];
[end critical seciton]
Now, I'm worried about the thread safety of accessing the delegate. In other words, how do the 2nd thread makes sure that the delegate is still valid when the delegate object can go away anytime without waiting for the operation completion.
The pseudo code above is the best attempt I've made and wonder if it's gonna actually work. Furthermore, I've never seen any attempt on making the delegate thread safe in similar work such as http://www.markj.net/iphone-asynchronous-table-image/ Isn't the critical section safe guarding necessary?
Thanks