Why dispatch_sync( ) call on main queue is blocking the main queue?

前端 未结 5 2093
花落未央
花落未央 2020-12-19 11:17

I know this is not a strong question but I have to clear my mind on this concept.

I have defined myBlock as follows.

void(^myBlock)(v         


        
5条回答
  •  -上瘾入骨i
    2020-12-19 12:09

    When you run an async task, it will create a new thread and your code in the block will be executed in that new thread. In that method you call dispatch_sync on main thread because you want to run in the main queue. Please try to understand it with this example.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    
        if ([NSThread isMainThread])
        {
            NSLog(@"Running on main Thread in dispatch_async");
        }
        else
        {
            NSLog(@"Running on another Thread in dispatch_async");
        }
    
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    
            if ([NSThread isMainThread])
            {
                NSLog(@"Running on main Thread in dispatch_sync");
            }
            else
            {
                NSLog(@"Running on another Thread in dispatch_sync");
            }
        });
    
        dispatch_sync(dispatch_get_main_queue(), ^(void) {
    
            if ([NSThread isMainThread])
            {
                NSLog(@"Running on main Thread in dispatch_sync");
            }
            else
            {
                NSLog(@"Running on another Thread in dispatch_sync");
            }
        });
    
    });
    

    Output is:

    Running on another Thread in dispatch_async
    Running on another Thread in dispatch_sync
    Running on main Thread in dispatch_sync

提交回复
热议问题