868
技術社區[雲棲]
再看Core Data中PSC陷入死鎖的問題
在《Core Data Programming Guide》文檔的Concurrency with Core Data這一章節中提到了“Use Thread Confinement to Support Concurrency”,這裏的“Thread”還包含serial operation queue和dispatch queue。
我目前的理解是MOC會負責對PSC進行加鎖解鎖,這些動作需要保證有序地得到執行,如果兩個thread同時訪問一份context,尤其是其中一個進行寫操作,另一個進行讀操作,就很容易發生死鎖:
- (void)runSave { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *moc = appDelegate.managedObjectContext; if (moc) { for (int j = 0; j < 10000; ++j) { NSString *threadPtr = [NSString stringWithFormat:@"%p", [NSThread currentThread]]; [_threadDict setObject:@"Running Thread" forKey:threadPtr]; People *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:moc]; people.name = @"noname"; } NSLog(@"**********IN SAVE %@", [NSThread currentThread]); NSError *error = nil; if ([moc save:&error]) { ; } NSLog(@"**********OUT SAVE %@", [NSThread currentThread]); } }); } - (void)runFetch { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *moc = appDelegate.managedObjectContext; if (moc) { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:[NSEntityDescription entityForName:@"People" inManagedObjectContext:moc]]; NSLog(@"~~~~~~~~~~IN FETCH %@", [NSThread currentThread]); NSError *error = NULL; NSArray *array = [moc executeFetchRequest:fetchRequest error:&error]; if (array) { ; } NSLog(@"~~~~~~~~~~OUT FETCH %@", [NSThread currentThread]); } }); }
死鎖的表現為:
最後更新:2017-04-03 14:53:58