Jak używać dispatch_queue_set_specific () i dispatch_get_specific ()
Trudno mi znaleźć dobre przykłady wykorzystania tych funkcji.
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)"];
}
});
Wynik
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)'
Czy jest to oczekiwane zachowanie? Gdybym miał dispatch_sync do kolejki1, ponieważ nie jestem w kolejce, zakleszczyłbym. czego mi brakuje?