-
-
Save JaviSoto/3933095 to your computer and use it in GitHub Desktop.
Simple main thread usage detector that I'm using in PSPDFKit to find performance problems early on.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Smart little helper to find main thread hangs. Enable in appDidFinishLaunching. | |
// Only available with source code in DEBUG mode. | |
@interface PSPDFHangDetector : NSObject | |
+ (void)startHangDetector; | |
@end | |
@implementation PSPDFHangDetector | |
+ (void)startHangDetector { | |
#ifdef DEBUG | |
NSThread *hangDetectionThread = [[NSThread alloc] initWithTarget:self selector:@selector(deadThreadMain) object:nil]; | |
[hangDetectionThread start]; | |
#endif | |
} | |
#ifdef DEBUG | |
static volatile NSInteger DEAD_SIGNAL = 0; | |
+ (void)deadThreadTick { | |
if (DEAD_SIGNAL == 1) { | |
NSLog(@"Main Thread doesn't answer..."); | |
} | |
DEAD_SIGNAL = 1; | |
dispatch_async(dispatch_get_main_queue(), ^{DEAD_SIGNAL = 0;}); | |
} | |
+ (void)deadThreadMain { | |
[NSThread currentThread].name = @"PSPDFHangDetection"; | |
@autoreleasepool { | |
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(deadThreadTick) userInfo:nil repeats:YES]; | |
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]; | |
} | |
} | |
#endif | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment