gpt4 book ai didi

multithreading - 核心数据专用队列死锁

转载 作者:行者123 更新时间:2023-12-04 06:50:54 25 4
gpt4 key购买 nike

我有一个后台线程做一些处理,并保存到核心数据。在我的应用委托(delegate)的 applicationShouldTerminate 中,我等待后台线程完成其工作时释放的信号量。这是为了避免线程在其工作过程中终止并使事情处于不一致状态。

不幸的是,这会导致死锁。以下是后台作业的运作方式:

_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_context setParentContext:_parentContext];

[_context performBlock:
^{
// ... long-running task here ...

NSError * error;
[_context save:&error]; // deadlock here if main thread is waiting on semaphore

// ... release semaphore here ...
}];

如果用户在后台线程仍在工作时退出应用程序,它就会死锁。问题似乎是 [_context save:&error] 正在调用 dispatch_sync (或等效的)进入主线程 - 但主线程已经在等待这个线程释放信号量,因此无法运行该 block 。

既然子上下文保存似乎阻塞在主线程上,那么如何实现这种模式(主线程等待子上下文完成并保存其上下文)?

主线程:

#0  0x00007fff882e96c2 in semaphore_wait_trap ()
#1 0x00007fff876264c2 in _dispatch_semaphore_wait_slow ()
#2 0x00000001001157fb in +[IndxCore waitForBackgroundJobs] at /Users/mspong/dev/Indx/IndxCore/IndxCore/IndxCore.m:48
#3 0x00000001000040c6 in -[RHAppDelegate applicationShouldTerminate:] at /Users/mspong/dev/Indx/Indx/Indx/RHAppDelegate.m:324
#4 0x00007fff9071a48f in -[NSApplication _docController:shouldTerminate:] ()
#5 0x00007fff9071a39e in __91-[NSDocumentController(NSInternal) _closeAllDocumentsWithDelegate:shouldTerminateSelector:]_block_invoke_0 ()
#6 0x00007fff9071a23a in -[NSDocumentController(NSInternal) _closeAllDocumentsWithDelegate:shouldTerminateSelector:] ()
(snip)
#17 0x00007fff9048e656 in NSApplicationMain ()
#18 0x0000000100001e72 in main at /Users/mspong/dev/Indx/Indx/Indx/main.m:13
#19 0x00007fff8c4577e1 in start ()

后台线程:

#0  0x00007fff882e96c2 in semaphore_wait_trap ()
#1 0x00007fff87627c6e in _dispatch_thread_semaphore_wait ()
#2 0x00007fff87627ace in _dispatch_barrier_sync_f_slow ()
#3 0x00007fff8704a78c in _perform ()
#4 0x00007fff8704a5d2 in -[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:] ()
#5 0x00007fff8702c278 in -[NSManagedObjectContext save:] ()
#6 0x000000010011640d in __22-[Indexer updateIndex]_block_invoke_0 at /Users/mspong/dev/Indx/IndxCore/IndxCore/Indexer/Indexer.m:70
#7 0x00007fff87079b4f in developerSubmittedBlockToNSManagedObjectContextPerform_privateasync ()
#8 0x00007fff876230fa in _dispatch_client_callout ()
#9 0x00007fff876244c3 in _dispatch_queue_drain ()
#10 0x00007fff87624335 in _dispatch_queue_invoke ()
#11 0x00007fff87624207 in _dispatch_worker_thread2 ()
#12 0x00007fff88730ceb in _pthread_wqthread ()
#13 0x00007fff8871b1b1 in start_wqthread ()

最佳答案

applicationShouldTerminate: 中,您可以返回 NSTerminateLater 以延迟终止,直到后台上下文完成保存操作。

保存完成后调用

[[NSApplication sharedApplication] replyToApplicationShouldTerminate:YES];

退出应用程序。

关于multithreading - 核心数据专用队列死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12429767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com