main thread does dispatch_async on a concurrent queue in viewDidLoad, or within a method matters

大城市里の小女人 提交于 2019-12-05 15:18:55
Hamish

There is a hard limit of 64 GCD concurrent operations (per top level concurrent queue) that can be run together.

What's happening is you're submitting over 64 blocks to your concurrent queue, each of them getting blocked by the [NSThread sleepForTimeInterval:1.0f], forcing a new thread to be created for each operation. Therefore, once the thread limit is reached, it backs up and starts to block the main thread.

I have tested this with 100 "database write" operations (on device), and the main thread appears to be blocked until 36 operations have taken place (there are now only 64 operations left, therefore the main thread is now un-blocked).

The use of a singleton shouldn't cause you any problems, as you're calling methods to that synchronously, therefore there shouldn't be thread conflicts.

The simplest solution to this is just to use a single background serial queue for your "database write" operations. This way, only one thread is being created to handle the operation.

- (void)viewDidLoad {
    [super viewDidLoad];

    static dispatch_once_t t;

    dispatch_once(&t, ^{
        serialQueue = dispatch_queue_create("com.epam.halo.queue2", DISPATCH_QUEUE_SERIAL);
    });


    for (int i = 0; i < 100; i++) {
        [self testInsert:i];
    }

}

-(void)executeDatabaseStuff:(int)i {
    //this is to simulate writing to database
    NSLog(@"----------START--------- %d", i);
    [NSThread sleepForTimeInterval:1.0f];
    NSLog(@"--------FINISHED-------- %d", i);
}

-(void)testInsert:(int)i {
    NSLog(@"Start insert.... %d", i);
    dispatch_async(serialQueue, ^() {
        [self executeDatabaseStuff:i];
    });
    NSLog(@"End insert... %d", i);
}

I don't know why inserting dispatch_async(dispatch_get_main_queue(), ^() {} inside your for loop was working for you... I can only assume it was off-loading the "database writing" until after the interface had loaded.

Further resources on threads & GCD

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!