linux - 同一个进程的线程可以跑在不同的核上吗?

标签 linux multithreading operating-system multiprocess

一个进程生成的线程能否在多核系统的不同内核上运行?

假设我有一个进程 P,我从中生成了两个线程 t1 和 t2,它是一个具有两个内核 C1 和 C2 的多核系统。我的问题是:

  1. 线程 t1 和 t2 是否可以在与进程 P 相同的内存空间上运行?
  2. 线程 t1 能否在与运行 P 的进程不同的内核中执行? eg: 进程P在核心C1上运行,线程t1在核心C2上运行?

最佳答案

Can the threads spawned from a process run on different cores of a multicore system?

是的。假设硬件有多个内核,并且操作系统支持/允许这样做。 (现代操作系统确实支持它。是否允许通常取决于管理策略。)

Will the threads t1 and t2 run in the same memory space as process P?

是的。它们将使用相同的内存/虚拟地址空间。

Can a thread t1 execute in a different core than which process P is running on? For example, process P is running on the core C1 and thread t1 is running in core C2?

这个问题没有意义。

POSIX 进程没有执行代码的能力。执行代码的是进程线程。因此,“进程在核心 C1 上运行”的想法是荒谬的。

记住:每个(事件的)POSIX 进程至少一个线程。该进程从一个线程开始,如果需要,该线程可能会产生其他线程。线程到内核的实际分配是由操作系统完成的,并且会在进程的整个生命周期内发生变化。

这就是线程在现代操作系统中的工作方式。对于 Linux,当前(符合 POSIX 标准)实现线程的方式是在 2003 年的 Linux 2.6 中引入的。在 Linux 2.6 内核之前,Linux 没有真正的 native 线程。相反,它有一个名为 LinuxThreads 的工具:

"LinuxThreads had a number of problems, mainly owing to the implementation, which used the clone system call to create a new process sharing the parent's address space. For example, threads had distinct process identifiers, causing problems for signal handling; LinuxThreads used the signals SIGUSR1 and SIGUSR2 for inter-thread coordination, meaning these signals could not be used by programs."

(来自 Wikipedia .)

在(2003 年之前!)LinuxThreads 模型中,“线程”实际上是一个进程,一个进程可以与其他进程共享其地址空间。

关于linux - 同一个进程的线程可以跑在不同的核上吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60694850/

相关文章:

Linux shell 将变量值传递给主程序

linux - 为什么查找内存使用峰值会得到不同的结果?

c# - 是否有关于线程调度的简单而有意识的图表/算法?

file-io - 如何用 MPI_File_open 替换 MPI 中的现有文件

node.js - 如何跨平台移动 npm node_modules 文件夹?

linux - 从以 root 身份运行的 bash 脚本向用户添加 ssh key

linux - 在 bash (Linux) 中将命令的输出分配给变量时出错

c - Erlang c-nodes 随机崩溃,并出现双重释放、内存损坏 malloc 消息

C11线程编程

process - 硬件与软件在上下文切换中的作用