Dispatch_group_wait is waiting forever

I study how it works dispatch_async().

I tried this snippet in main():

typedef void(^VoidBlock)();

VoidBlock aBlock = ^{
    NSLog(@"do work in main queue");
};
dispatch_async(dispatch_get_main_queue(), aBlock);

But the block is never called. I thought that perhaps the main thread ends before the block starts. Then I tried this:

dispatch_group_t aGroup = dispatch_group_create();
VoidBlock aBlock = ^{
    NSLog(@"do work in main queue");
    dispatch_group_leave(aGroup);
};
dispatch_group_enter(aGroup);
dispatch_async(dispatch_get_main_queue(), aBlock);
dispatch_group_wait(aGroup, DISPATCH_TIME_FOREVER);

This also does not work (the block is not called). The difference is that now the main thread (correctly) blocks the operatordispatch_group_wait(aGroup, DISPATCH_TIME_FOREVER)

What is the problem?

+4
source share
2 answers

I suspect that you did not create an iOS project (or any other type of project that runs runloop), but a "Command Line Tool". If it is true:

Your first approach

, , main() (, , ), .

: , .

. wait , ( ), , , .

, , :

dispatch_group_t aGroup = dispatch_group_create();
VoidBlock aBlock = ^{
      NSLog(@"do work in main queue");
      dispatch_group_leave(aGroup);
};
dispatch_group_enter(aGroup);

 // dispatch on another queue than the one wait will block
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), aBlock);
dispatch_group_wait(aGroup, DISPATCH_TIME_FOREVER);

, (), () .


@Ishahaks answer, " " " ", ( "iOS",), main(). , iOS runloop (while(true) { // wait for events }), - main(). . Runloop.

+4

iOS, "" "" " ", application:didFinishLaunchingWithOptions :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    typedef void(^VoidBlock)();

    VoidBlock aBlock = ^{
        NSLog(@"do work in main queue");
    };
    dispatch_async(dispatch_get_main_queue(), aBlock);
    return YES;
}
0

Source: https://habr.com/ru/post/1662762/


All Articles