Linux当中Process与Thread的概念

来源:互联网 发布:网络翻唱歌手李洋 编辑:程序博客网 时间:2024/05/21 10:20

The four threads will have the same PID but only when viewed from above. What you (as a user) call a PID is not what the kernel (looking from below) calls a PID.

In the kernel, each thread has it's own ID, called a PID (although it would possibly make more sense to call this a TID) and they also have a TGID (thread group ID) which is the PID of the thread that started the whole process.

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 its TGID from the thread that created it.

That way, the kernel can happily schedule threads independent of what process they belong to, while processes (thread group IDs) are reported to you.

The following hierarchy of threads may help:

                      USER VIEW <-- PID 43 --> <----------------- PID 42 ----------------->                     +---------+                     | process |                    _| pid=42  |_                  _/ | tgid=42 | \_ (new thread) _       _ (fork) _/   +---------+                  \      /                                        +---------++---------+                                    | process || process |                                    | pid=44  || pid=43  |                                    | tgid=42 || tgid=43 |                                    +---------++---------+ <-- PID 43 --> <--------- PID 42 --------> <--- PID 44 --->                     KERNEL VIEW

You can see that starting a new process gives you a new PID and a new TGID (both set to the same value), while starting a new thread gives you a new PID while maintaining the same TGID as the thread that started it.

来源:http://stackoverflow.com/questions/9305992/linux-threads-and-process

0 0
原创粉丝点击