Lingzt Lingzt - 3 months ago 19
Objective-C Question

How many threads do we run in this code sample? Can anyone draw a flowchart of it?

- (void)viewDidLoad {
[super viewDidLoad];

[self firstTest];
}

-(void)viewWillAppear:(BOOL)animated{
[self secondTest];
}

-(void)viewDidAppear:(BOOL)animated{
[self thirdTest];
}

- (void)firstTest {
NSLog(@"=================1");

dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"=================2");
});

NSLog(@"=================3");
}

- (void)secondTest {
NSLog(@"ViewWillAppear=============");

dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"=================4");

dispatch_sync(dispatch_get_main_queue(), ^{
[NSThread sleepForTimeInterval:5.0f];

NSLog(@"=================5");
});

NSLog(@"=================6");
});

NSLog(@"==========Main Thread Blocked");
}

- (void)thirdTest {
NSLog(@"ViewDidAppear=============");

dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"=================7");

dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"=================8");
});

NSLog(@"=================9");
});
}

Rob Rob
Answer

Each of the dispatch_async(dispatch_get_global_queue(...)) may be run on a worker thread managed by the global queue, so you're potentially looking at three threads, but it's also possible that the first dispatch to the global queue may finish before the second starts, so you may actually end up using two threads, but given that you dispatch synchronously in secondTest, you'll almost certainly use three threads.

So the main thread will run 1, 3, 2, 5, and 8, a worker thread invoked by the global queue in secondTest will run 4 and 6, and a worker thread in thirdTest will run 7 and 9.

Comments