gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:27:04 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com