dispatch_queue_set_specific就是向指定队列里面设置一个标识 如:
dispatch_queue_set_specific(queue1, queueKey1, &queueKey1,NULL);
就是向queue1对了中设置一个queueKey1标识。
dispatch_get_specific就是在当前队列中取出标识,注意iOS中线程和队列的关系,所有的动作都是在队列中执行的!
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
static void *queueKey1 = "queueKey1";
dispatch_queue_t queue1 = dispatch_queue_create(queueKey1, DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(queue1, queueKey1, &queueKey1, NULL);
NSLog(@"1. 当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
if (dispatch_get_specific(queueKey1)) {
//当前队列是主队列,不是queue1队列,所以取不到queueKey1对应的值,故而不执行
NSLog(@"2. 当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
[NSThread sleepForTimeInterval:1];
}else{
NSLog(@"3. 当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
[NSThread sleepForTimeInterval:1];
}
dispatch_sync(queue1, ^{
NSLog(@"4. 当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
[NSThread sleepForTimeInterval:1];
if (dispatch_get_specific(queueKey1)) {
//当前队列是queue1队列,所以能取到queueKey1对应的值,故而执行
NSLog(@"5. 当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
[NSThread sleepForTimeInterval:1];
}else{
NSLog(@"6. 当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
[NSThread sleepForTimeInterval:1];
}
});
dispatch_async(queue1, ^{
NSLog(@"7. t当前线程是: %@, 当前队列是: %@ 。",[NSThread currentThread],dispatch_get_current_queue());
[NSThread sleepForTimeInterval:1];
});
[NSThread sleepForTimeInterval:5];
}
return 0;
}
输出结果:
2016-02-19 14:31:23.390 gcd[96865:820267] 1.当前线程是: <NSThread: 0x1001053e0>{number = 1, name = main},当前队列是: <OS_dispatch_queue: com.apple.main-thread[0x100059ac0]>。
2016-02-19 14:31:23.391 gcd[96865:820267] 3.当前线程是: <NSThread: 0x1001053e0>{number = 1, name = main},当前队列是: <OS_dispatch_queue: com.apple.main-thread[0x100059ac0]>。
2016-02-19 14:31:24.396 gcd[96865:820267] 4.当前线程是: <NSThread: 0x1001053e0>{number = 1, name = main},当前队列是: <OS_dispatch_queue: queueKey1[0x103000000]>。
2016-02-19 14:31:25.400 gcd[96865:820267] 5.当前线程是: <NSThread: 0x1001053e0>{number = 1, name = main},当前队列是: <OS_dispatch_queue: queueKey1[0x103000000]>。
2016-02-19 14:31:26.402 gcd[96865:820367] 7. t当前线程是: <NSThread: 0x100105e10>{number = 2, name = (null)},当前队列是: <OS_dispatch_queue: queueKey1[0x103000000]>。
Program ended with exit code: 0
网友评论