我很难找到如何使用这些功能的好例子。
static void * kQueue1Key = "key1";
static void * kQueue2Key = "key2";
dispatch_queue_t queue1 = dispatch_queue_create("com.company.queue1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue2 = dispatch_queue_create("com.company.queue2", DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(queue1, kQueue1Key, (void *)kQueue1Key, NULL);
dispatch_queue_set_specific(queue2, kQueue2Key, (void *)kQueue2Key, NULL);
dispatch_sync(queue1, ^{
if(dispatch_get_specific(kQueue1Key))
{
NSLog(@"I'm expecting this line to run (A)");
dispatch_sync(queue2, ^{
NSLog(@"I'm expecting this line to run (B)");
if(dispatch_get_specific(kQueue2Key))
{
if(dispatch_get_specific(kQueue1Key))
{
NSLog(@"I'm expecting this line to run (C)");
}
else
{
[NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
}
}
else
{
[NSException raise:NSInternalInconsistencyException format:@"Should not end up here (B)"];
}
});
}
else
{
[NSException raise:NSInternalInconsistencyException format:@"Should not end up here (A)"];
}
});
结果
I'm expecting this line to run (A)
I'm expecting this line to run (B)
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Should not end up here (C)'
这是预期的行为吗?如果我将 dispatch_sync 到 queue1,因为我不在队列中,我会死锁。我错过了什么?