The program pstree and htop showing threads with unique PIDS. How is this possible?
Solution 1
The mistake was to presume those numbers were PIDS, when in fact they are TIDS (thread IDs). See Linux function gettid(2). Reading up on clone(2) gives a lot of extra (and interesting) details.
Solution 2
Threads are often different processes. At least in Linux, a "thread" is often a clone of the process which happens to share some memory with the parent process.
However, in some language, threads do stay part of the main process because they are "Green" threads, which are simulated in the language VM. Java and python are famous for this.
Related videos on Youtube
stantona
Updated on September 18, 2022Comments
-
stantona over 1 year
I ran the program pstree -p 31872 which printed the following output:
ruby(31872)─┬─{ruby}(31906) └─{ruby}(32372)
The man page for pstree says:
Child threads of a process are found under the parent process and are shown with the process name in curly braces, e.g.
icecast2---13*[{icecast2}]
(The above is displayed differently because of the missing -p option, which disables compaction.)
Running pstree 31872 without -p gives:
ruby───2*[{ruby}]
When I try to observe those PIDS using ps, no results are found. However, the pids, exist in /proc.
My question is, why would threads have different pids? I would expect them to be the same (31872) as the process. The same behavior is observed when running htop.
-
stantona over 9 yearsThreads belong to processes and share the process's memory space. They are definitely not a separate process from the process that created them. When you say "a thread is often a clone of a process", you might be thinking of the fork system call, which creates a child process, not a thread.
-
stantona over 9 yearsI think you kind of elaborated on what I said, no??
-
Hack Saw over 9 yearsMore succinctly, the only difference between real threads and processes, in linux, is that a threads shares memory with another process, and a process doesn't. As far as the proc directory goes, and the machinery behind it, and more importantly the scheduler, it's just another process.