What is the need to check if a thread is the main thread before sending sync?

SDWebImage uses the following code in the SDWebImageManager image download code. Why is it necessary to check if a thread is the main thread instead of doing dispatch_sync independently?

#define dispatch_main_sync_safe(block)\
    if ([NSThread isMainThread])\
    {\
        block();\
    }\
    else\
    {\
        dispatch_sync(dispatch_get_main_queue(), block);\
    }
+4
source share
1 answer

Sending a block synchronously to the current current queue leads to an immediate deadlock. You can easily verify by executing the following code in the main thread / queue:

NSLog(@"before");
dispatch_sync(dispatch_get_main_queue(), ^{
    NSLog(@"in block");
});
NSLog(@"after");

, , , if ([NSThread isMainThread]). ( , " " " " .)

, dispatch_async().

+4

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


All Articles