iOS gcd dispatch使用注意

class ViewController: UIViewController {
    var dbQueue:dispatch_queue_t = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        dbQueue = dispatch_queue_create("com.Innocellence.sunflower", nil)
    
        //do some work in dbQueue from main thread
        dispatch_sync(dbQueue, { () -> Void in
  
            //do some work in main thread from dbQueue
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                self.test()
            })
            
        })
        
        println("this is some other code")

    }
    
    func test(){
        
        println("this is test")
    
    
    }


}

 

上面这段代码,是错误的,viewdidload无法执行完

再把代码稍微换下

 

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        dbQueue = dispatch_queue_create("com.Innocellence.sunflower", nil)
    
        //do some work in dbQueue from main thread
        dispatch_async(dbQueue, { () -> Void in
  
            //do some work in main thread from dbQueue
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                self.test()
            })
            
        })
        
        println("this is some other code")

    }

这个是有输出的,结果是

this is some other code

this is test

 

再变成下面这个

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        dbQueue = dispatch_queue_create("com.Innocellence.sunflower", nil)
    
        //do some work in dbQueue from main thread
        dispatch_sync(dbQueue, { () -> Void in
  
            //do some work in main thread from dbQueue
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.test()
            })
            
        })
        
        println("this is some other code")

    }

输出如下

this is some other code


this is test

第一个为什么无法继续执行了呢,首先代码阻塞了主线程的执行,要求在新线程执行完后才返回,但是新线程也被阻塞了,要求代码在主线程完成后才能返回,这样就形成了循环。这里线程这个词用的不准,其实紧紧是线程中执行的一段顺序代码。还需要仔细研究原因!

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。