CMainThreadDetector
检测主线程卡顿,输出卡顿发生时的堆栈信息. Detect main thread slow ,and output stack symbols.
Install / Use
/learn @chbo297/CMainThreadDetectorREADME
CMainThreadDetector
检测主线程卡顿,输出卡顿时的堆栈信息.帮助开发者找到 app 中发生卡顿的位置。
Detect main thread slow ,and output stack symbols.
原理
开启一个子线程,
每隔一段时间ping一下主线程(比如一帧的时间1/60s),主线程pong反馈,
如果超时未响应,则代表主线程卡住了。
此时发送中断信号,强制中断主线程并输出当前堆栈信息。
使用方法
调用[[CMainThreadDetector sharedDetector] startDetecting]开启检测,比如可以在程序启动后开启:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[CMainThreadDetector sharedDetector] startDetecting];
return YES;
}

如上图,点击下侧按钮,按下后会在主线程进行一次长时间运算,模拟一次卡顿的发生。
检测器监测到卡顿,输出了堆栈信息,
向下找到了[ViewController blockingTheMainThread]的栈信息,
这个方法里调用了大量操作使主线程发生了卡顿。
配置
可以通过设置这两个值调整监测的频率和阈值。
#define DETECT_INTERVAL 0.1f
#define DETECT_TIMELIMIT (1.0f/60.0f)
可以通过设置delegate获取输出的堆栈,自行存储在文件中。
需要注意的是,demo不可以在调试环境测试,因为调试环境下gdb也在向主线程发送signal,导致detector的signal失效,在Xcode中不停的中断,测试时,安装到虚拟机/手机上运行即可。
Related Skills
node-connect
350.1kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
109.9kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
350.1kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
350.1kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
