纪忠懿
纪忠懿

Reputation: 124

Why Dispatch_group_notify works different in different environment?

The first situation is that I create a Command Line Tool Application,and run this code.

    NSLog(@"Main:%@", [NSThread currentThread]);

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, queue, ^{
        NSLog(@"Task1:%@", [NSThread currentThread]);
    });

    dispatch_group_async(group, queue, ^{
        NSLog(@"Task2:%@", [NSThread currentThread]);
    });

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"Finish:%@", [NSThread currentThread]);
    });

The log in terminal is

    Main:<NSThread: 0x1028033b0>{number = 1, name = main}
    Task2:<NSThread: 0x10040f0f0>{number = 2, name = (null)}
    Task1:<NSThread: 0x1006008d0>{number = 3, name = (null)}

If I want to show last log in queue and replace the main queue

     dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"Finish:%@", [NSThread currentThread]);
    });

with queue

     dispatch_group_notify(group, queue, ^{
        NSLog(@"Finish:%@", [NSThread currentThread]);
    });

The terminal print the last log.But why it can't revoke in Main queue?

When i copy this code to simple iOS Application.All works well:

Main:<NSThread: 0x600000070ac0>{number = 1, name = main}
Task2:<NSThread: 0x6000002633c0>{number = 3, name = (null)}
Task1:<NSThread: 0x600000263480>{number = 4, name = (null)}
MainFinish:<NSThread: 0x600000070ac0>{number = 1, name = main}

And I try to add sleep(1) over Task1 in 'Command Tool Line', but it seems block the queue and only print log:Task2.... But this all works well in simple iOS Application.

Why lead to these different?

Upvotes: 1

Views: 359

Answers (1)

jimmy
jimmy

Reputation: 26

image here

Unlike other queues that active on created,you should call dispatch_main() method to execute blocks submitted to main thread

image here

The reason for the same code runs well in iOS Application is that the application start a default runloop which execute the task submitted to the main queue according to a certain rule like UI update notification.

The reference as follow:

swift-corelibs-libdispatch

Concurrency Programming Guide

Upvotes: 1

Related Questions