當NSOperation子類化完成一小部分工作時,我發現它很容易陷入僵局。下面我有一個玩具的例子,很容易理解爲什麼它永遠不會完成。異步可可 - 在NSOperation中防止「簡單」(明顯)死鎖?
我似乎只能通過解決方案來防止來自主叫方的死鎖,而不是被叫方。例如,調用者可以繼續運行運行循環,而不是等待結束等。如果主線程在操作期間需要同步消息,那麼我想知道是否存在操作子類可以實現的規範解決方案防止這種類型的死鎖。我纔剛剛開始沾我的腳趾在異步編程...
@interface ToyOperation : NSOperation
@end
@implementation ToyOperation
- (void)main
{
// Lots of work
NSString *string = @"Important Message";
[self performSelector:@selector(sendMainThreadSensitiveMessage:) onThread:[NSThread mainThread] withObject:string waitUntilDone:YES];
// Lots more work
}
- (void)sendMainThreadSensitiveMessage:(NSString *)string
{
// Update the UI or something that requires the main thread...
}
@end
- (int)main
{
ToyOperation *op = [[ToyOperation alloc] init];
NSOperationQueue *opQ = [[NSOperationQueue alloc] init];
[opQ addOperations: @[ op ] waitUntilFinished:YES]; // Deadlock
return;
}