我正在努力让多线程应用程序在多个内核上运行。我研究了亲和性、调度等。有没有办法找出任何线程正在运行的 CPU Id?我现在正在使用 sched_getaffinity - 但我认为这与进程 ID 有关,而不是进程中的线程。多线程应用程序在 Windows 上运行良好,但在 Linux 上似乎受 CPU 限制(仅使用一个 CPU)
更新:
如果我的 Linux 应用程序启动 64 个线程——我仍然只有一个 pid,对吗?我的理解是每个启动的线程都可以在目标硬件的不同 CPU/内核上运行,对吗?
这里有一个示例应用程序:How do I make a multi-threaded app use all the cores on Ubuntu under VMWare?
最佳答案
你的第一个问题
Is there a way to find out the CPU Id that any thread is running on? I'm using sched_getaffinity now
sched_getaffinity
不返回 CPU,它返回符合条件的 CPU 的掩码。它说:
The affinity mask is actually a per-thread attribute that can be adjusted independently for each of the threads in a thread group.
然后
If you are using the POSIX threads API, then use pthread_setaffinity_np(3) instead of sched_setaffinity().
为了简单地找出所使用的 CPU,/proc/[pid]/stat
有一个“处理器”字段:
processor
%d (since Linux 2.2.8) CPU number last executed on.
你的第二个问题:
The mulit-threaded app works great on Windows, but seems to be CPU bound (using only one CPU) on linux
显示出现此问题的最小示例。
关于linux - 是否可以在 Linux 上使用 pthreads 打印 CPU 和核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6549463/