iOS开发心得

dispatch_sync()死锁问题个人疑问

2015-11-25  本文已影响1370人  小樊
源码块一:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@",[NSThread currentThread]);  
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"Hello World");
    });
}

分析:

源码块二:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"1-----%@",[NSThread currentThread]);
    
    //创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
    
    //异步函数产生一个新的线程
    dispatch_async(queue, ^{
        NSLog(@"2-----%@",[NSThread currentThread]);
        
       //向新线程中用同步函数dispatch_sync()追加任务
        dispatch_sync(queue, ^{
            NSLog(@"3-----%@",[NSThread currentThread]);
        });
    });   
}

控制台:
1-----<NSThread: 0x7ff8aad00220>{number = 1, name = main}
2-----<NSThread: 0x7ff8aad11670>{number = 2, name = (null)}

分析:

源码块三:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"1-----%@",[NSThread currentThread]);
    
    //创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
    
    //异步函数产生一个新的线程
    dispatch_async(queue, ^{
        NSLog(@"2-----%@",[NSThread currentThread]);
        
        //创建一个新的串行队列
        dispatch_queue_t queue2 = dispatch_queue_create("newQueue", DISPATCH_QUEUE_SERIAL);
       
        //在新线程中用同步函数dispatch_sync()向新建的串行队列中追加任务
        dispatch_sync(queue2, ^{
            NSLog(@"3-----%@",[NSThread currentThread]);
        });
    });
    
}

控制台:
1-----<NSThread: 0x7fe5daf01730>{number = 1, name = main}
2-----<NSThread: 0x7fe5dac448f0>{number = 2, name = (null)}
3-----<NSThread: 0x7fe5dac448f0>{number = 2, name = (null)}

可以看到该代码块并没有产生死锁,但是queue2队列也是在新线程中,为什么调用dispatch_sync()函数时,并没有阻塞<NSThread: 0x7fe5dac448f0>{number = 2, name = (null)}这条线程,从而使得dispatch_sync()中的任务在新线程中被执行.

那么我的问题就是: 用异步函数创建新线程时所用到的队列,即代码中的queue

dispatch_async(queue, ^{
        NSLog(@"2-----%@",[NSThread currentThread]);

如果为串行队列(并发队列并不会有该情况),那么该队列 是否可以认为是 该新线程中的 "主队列",类似于源码块一的效果.

上一篇 下一篇

猜你喜欢

热点阅读