linux - 内核如何区分线程和进程

标签 linux multithreading process kernel

在 Linux 中线程被称为轻量级进程。无论是进程还是线程,都是通过task_struct数据结构来实现的。

1> 那么,从这个意义上讲,内核如何区分线程和进程?

2> 当发生上下文切换时,线程如何在上下文切换中获得更少的开销?因为在这个线程之前,另一个进程的另一个线程可能正在运行。因此,即使资源在进程的线程之间共享,内核也应该加载所有资源。

最佳答案

how kernel distinguishes between thread and process.

来自 http://www.kernel.org/doc/ols/2002/ols2002-pages-330-337.pdf来自Linux - Threads and Process

This was addressed during the 2.4 development cycle with the addition of a concept called a ’thread group’. There is a linked list of all tasks that are part of the thread group, and there is an ID that represents the group, called the tgid. This ID is actually the pid of the first task in the group (pid is the task ID assigned with a Linux task), similar to the way sessions and process groups work. This feature is enabled via a flag to clone().

在内核中,每个线程都有自己的 ID,称为 PID(尽管将其称为 TID 或线程 ID 可能更有意义)并且它们还有一个 TGID(线程组 ID),即 PID启动整个过程的线程。

Simplistically, when a new process is created, it appears as a thread where both the PID and TGID are the same (new) number.

When a thread starts another thread, that started thread gets its own PID (so the scheduler can schedule it independently) but it inherits the TGID from the original thread.

所以主线程是具有相同 PID 和 TGID 的线程,这个 PID 是进程 PID。一个线程(但不是主线程)具有不同的 PID 但具有相同的 TID。

关于linux - 内核如何区分线程和进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213681/

相关文章:

python - 如何终止使用 shell=True 启动的 python 子进程

linux - 如何通过网络写入文件

c++ - C++控制台应用程序未返回

c++ - 仔细检查锁定问题,c++

c++ - 自动将子进程附加到调试器

c++ - 为什么我的字符串在 Windows 和 Linux 上通过 strtok 解析不同?

java - 在执行线程上运行 Spring 方面建议

python - 来自 Process 的简单 wxPython post 事件

java - Android(事物): How to do clean-up before program ends?

c - C 程序中的内存损坏/双重释放问题