You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用perf或其他工具剖析处于等待状态的线程?

多线程程序中剖析挂起线程与锁竞争的方案

问题背景

需要分析多线程程序中处于锁等待、休眠或调度挂起状态的线程,同时希望在火焰图中结合CPU栈追踪与锁竞争信息。尝试过gperftools(仅追踪CPU占用线程)和perf默认采样(无法捕获挂起线程栈),测试程序及操作如下:

测试程序

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
    
void *threadfunction(void *arg)
{
    pthread_mutex_t* mutex  =  arg;

    pthread_mutex_lock(mutex);
    printf("I am the thread function!\n");
    pthread_mutex_unlock(mutex);
}

int main(void)
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, 0);
    pthread_mutex_lock(&mutex);

    pthread_t thread;
    (void) pthread_create(&thread, NULL, threadfunction, &mutex);
    
    for (int i = 0; i < 60000000; i++)
        printf("I am the main function!\n");

    pthread_mutex_unlock(&mutex);

    (void) pthread_join(thread, NULL);

    return 0;
}

之前的操作

执行默认perf采样:

perf record -F50 --call-graph dwarf test_program

生成火焰图:

perf script > perf.script
stackcollapse-perf.pl perf.script | flamegraph.pl > flamegraph.svg

结果仅显示主线程栈,锁等待的子线程栈未被捕获。


解决方案

一、用perf同时追踪CPU运行与锁等待事件

要同时捕获运行中线程的CPU栈和挂起线程的锁等待栈,需要指定多个事件并开启调用栈追踪:

perf record -F50 -e cpu-clock,sched:sched_switch,lock:pthread_mutex_lock -g --call-graph dwarf ./test_program
  • -e cpu-clock:采样正在占用CPU的线程栈
  • -e sched:sched_switch:追踪线程调度切换事件,捕捉线程挂起/唤醒的时机
  • -e lock:pthread_mutex_lock:专门追踪pthread_mutex的锁等待事件,记录等待线程的调用栈
  • -g --call-graph dwarf:生成带调用栈的信息,dwarf格式能提供更精准的栈回溯

生成火焰图时,直接用常规流程即可,栈折叠工具会自动处理多事件的栈信息:

perf script > perf.script
stackcollapse-perf.pl perf.script | flamegraph.pl --color=lock > combined_flamegraph.svg

--color=lock参数会让锁相关的栈帧显示为橙色,更直观区分锁等待逻辑。

二、用perf lock专门分析锁竞争

如果重点关注锁竞争,可以用perf的lock子命令:

  1. 记录锁事件:
perf lock record ./test_program
  1. 查看锁竞争统计:
perf lock report
  1. 生成锁等待的火焰图:
perf lock report -g | stackcollapse-perf.pl | flamegraph.pl > lock_only_flamegraph.svg

这个火焰图会聚焦在锁等待的调用栈上,能清晰看到哪个锁被哪个线程长时间等待。

三、其他工具选项

  • bcc工具集:其中的mutex或lockstat工具可以实时追踪锁等待,支持生成火焰图,适合动态追踪场景
  • trace-cmd:基于ftrace的工具,能追踪内核调度和锁事件,结合栈回溯也能分析挂起线程,但上手门槛略高

内容的提问来源于stack exchange,提问作者Yunus King

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:17