0
votes
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"begin async:%@", [NSThread currentThread]);
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"in sync:%@", [NSThread currentThread]);
        });
        NSLog(@"end async:%@", [NSThread currentThread]);
    });
    NSLog(@"end main");
}

Why do I get such result as below?

  1. end main
  2. begin async:{number = 2, name = (null)}
  3. in sync:{number = 2, name = (null)}
  4. end async:{number = 2, name = (null)}

As apple developer document said:

Submits a block to a dispatch queue for synchronous execution. Unlike dispatch_async, this function does not return until the block has finished. Calling this function and targeting the current queue results in deadlock.

"in sync" and "end async" will never log out, is that correct?

1
The system queues are concurrent, so they can run multiple blocks at the same time and won't deadlock - dan
Can u try "dispatch_get_main_queue" instead of "dispatch_get_global_queue"? - Ruchira Randana
@dan thank you, i found Apple says [Returns a system-defined global concurrent queue with the specified quality of service class.] - chopper

1 Answers

0
votes

But try this, if you want to see a deadlock:

@interface ViewController ()
@property dispatch_queue_t q;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.q = dispatch_queue_create("myq", nil);
    dispatch_sync(self.q, ^{
        NSLog(@"begin sync1:%@", [NSThread currentThread]);
        dispatch_sync(self.q, ^{
            NSLog(@"in sync2:%@", [NSThread currentThread]);
        });
        NSLog(@"end sync1:%@", [NSThread currentThread]);
    });
    NSLog(@"end main");

}

@end