linux - 是否可以在 Linux 上使用 pthreads 打印 CPU 和核心

标签 linux multithreading pthreads

我正在努力让多线程应用程序在多个内核上运行。我研究了亲和性、调度等。有没有办法找出任何线程正在运行的 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/

相关文章:

linux - Solaris 如何将最近更新的多个文件复制到另一个目录

c - Linux 如何知道要调用哪个 ioctl 函数?

linux - Linux 内核中的上下文切换时间

java - 使用多线程连接到 MySQL 数据库

c - 数据库事务和线程

c++ - Windows 上的进程资源限制

linux - 删除文件中的数据范围

c# - 异步向主线程发送信号

c++ - 如何加入在c/c++中动态创建的线程

c - 为什么多个线程得到相同的 "tid?"