我正在用C / C ++编写一个多线程程序,其目标是Linux机器。
是否可以检测其中一个线程何时进行上下文切换(即暂停)?注意,我不想知道线程是否还活着,我想知道它是否正在运行。
答案 0 :(得分:0)
您可以使用ps输出中的STAT列来了解进程/线程的确切状态。
在linux中,线程只不过是共享相同代码,数据段和堆段的进程。
可以在以下位置找到ps命令的示例输出以及如何解释 https://unix.stackexchange.com/questions/18474/what-does-this-process-stat-indicates
答案 1 :(得分:0)
是否可以检测其中一个线程何时进行上下文切换(即暂停)?
至于你的问题是否有可能 - 它认为是可能的。至少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):
其次跟踪事件可从用户空间使用!我们不需要 编写内核模块以便能够挂钩,但显然我们 只能这样读取数据
如果您能够发现它并稍后回答您自己的问题,那将会很棒。