【问题标题】:Is it possible to detect that a thread was context-switched in Linux [suspended]?是否可以检测到一个线程在 Linux [暂停] 中进行了上下文切换?
【发布时间】:2015-09-29 11:50:47
【问题描述】:

我正在用 C/C++ 编写一个多线程程序,目标是 Linux 机器。

是否可以检测其中一个线程何时切换上下文(即暂停)?注意,我不想知道线程是否还活着,我想知道它当前是否正在运行。

【问题讨论】:

  • 您如何考虑使用这些信息?您想从同一个可执行文件中的另一个线程中查找,还是从不同的进程中查找?
  • 来自不同的线程。我想从线程 0 检查线程 1...N 当前是否正在运行。我正在实现一个工作窃取算法。
  • 此类信息在收到时已过时。
  • 我认为你不能。您需要知道这一点的原因是什么?
  • 我对这个话题不是很了解,但是这本书Understanding the Linux Kernel,第 3 章,非常深入地介绍了 Linux 如何管理进程和线程,包括内核用来跟踪这些事情的结构.虽然可能无法从用户空间获得,但您可以创建一个内核驱动程序,允许用户空间程序在特定线程/进程更改状态时查询或接收通知。 (我与这本书或 O'Reilly 无关,顺便说一句,我只是拥有它)

标签: c++ linux multithreading linux-kernel pthreads


【解决方案1】:

是否可以检测到其中一个线程何时切换上下文(即暂停)?

至于你的问题是否可能 - 它认为这是可能的。至少 SystemTap (https://sourceware.org/systemtap/) 可以做到。

SystemTap 有一个脚本可以让用户查看特定 PID (https://sourceware.org/systemtap/examples/profiling/sched_switch.stp) 的上下文切换:

probe scheduler.ctxswitch
{
    if (target_pid != 0
        && next_pid != target_pid
        && prev_pid != target_pid)
            next

    if (target_name != ""
        && prev_task_name != target_name
        && next_task_name != target_name)
            next

    printf("%-16s%5d %5d %5d:%5d:%s ==> %5d:%5d:%s %-16s\n",prev_task_name,
        task_cpu(prev_task),gettimeofday_ns(),prev_pid,prev_priority,state_calc(prevtsk_state),next_pid,
        next_priority,state_calc(nexttsk_state),next_task_name)
}

据我所知 SystemTap 编译 STP 文件,然后放入 Linux 内核并显示信息。

我不知道如何在用户空间和 C++ 程序中获取这些信息。不过,这似乎也是可能的 (http://netsplit.com/tracing-on-linux):

第二个跟踪事件可以从用户空间使用!我们不需要 编写内核模块以便能够连接到它们,但显然我们 只能这样读取数据

因此,如果您能发现它并稍后回答您自己的问题,那就太好了。

【讨论】:

    【解决方案2】:

    您可以使用 ps 输出中的 STAT 列来了解进程/线程的确切状态。

    在linux中,线程只不过是共享相同代码、数据段和堆段的进程。

    可以在以下位置找到 ps 命令的示例输出以及如何解释 https://unix.stackexchange.com/questions/18474/what-does-this-process-stat-indicates

    【讨论】:

    • 这与问题有什么关系?
    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 2022-10-17
    • 2011-07-23
    • 1970-01-01
    • 2011-08-22
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多