Making sure I correctly explain the nested GCD

So I put 10 tasks in a parallel queue using dispatch_async . They do not block the next task and are processed in order. My user interface is responsive.

for (int i = 0; i < 10; i++) {

    dispatch_async(concurrencyQueue, ^() {

        NSLog(@"..calling insertion method to insert record %d", i);

           dispatch_sync(serialQueue, ^() {

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

        });

    });
}

For each task, we simulate writing to the database with a “1 second sleep” in a sequential queue via dispatch_sync .

I always thought that dispatch_sync blocks everyone and synchronizes their tasks, because this is how it behaves when I use it individually. However, in this situation, it does not block the main thread. Instead, it works beautifully in the background as I want.

Is it because any thread is associated with the queue?

, dispatch_async .

dispatch_sync , . , dispatch_sync , .

?

!

+1
2

, concurrencyQueue, serialQueue. .

sleep serialQueue. , serialQueue.

, serialQueue dispatch_sync, . , NSLog dispatch_sync.

for (int i = 0; i < 10; i++) {
    dispatch_async(concurrencyQueue, ^() {
        NSLog(@"..calling insertion method to insert record %d", i);

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

        NSLog(@"..called insertion method to insert record %d", i);
    });
}

2- NSLog dispatch_sync , dispatch_sync dispatch_async.

+3

, . dispatch_sync() , .

+2

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


All Articles