Thread number obtained via Thread.list.size does not match one via / proc

Look at the code first:

#!/usr/bin/env ruby
# encoding: UTF-8

thread_num = Thread.list.size
thread_num_via_proc = thread_num_later = nil
IO.readlines("/proc/#{Process.pid}/status").each do |line|
  if line.start_with?("Threads:")
    thread_num_via_proc = line.split[1].to_i
    thread_num_later = Thread.list.size
  end
end

p thread_num # 1
p thread_num_via_proc # 2
p thread_num_later # 1

      

The stream number obtained from / proc / [pid] / status is always equal Thread.list.size + 1

.

Then I mentioned man proc

and he says (which confused me):

  • Topics: The number of threads in a process containing this branch.

There must be something I misunderstood about "Thread.list" or "/ proc / [pid] / status", can anyone point this out?

+3


source to share


1 answer


I think your program is perfectly correct, although it will obviously only work on systems that display process information via / proc in that particular format.

Ruby Thread#list

gives you a ruby ​​view of the running threads available to your program - you have 1 default thread main

and you can create others withThread#new

/proc/pid/status

gives you the number of operating systems (native) threads. If you test any ruby ​​program, at least on Linux, you will see that it always spawns two threads.

eg. if you query the current ruby ​​process with ps -Lf

, you will see entries for each thread with a different LWP value , and the number of threads displayed in NLWP



here's my output for irb session

$ ps -Lfp 18991
UID        PID  PPID   LWP  C NLWP STIME TTY          TIME CMD
vagrant  18991 18906 18991  0    2 09:03 pts/9    00:00:00 irb                                              
vagrant  18991 18906 18992  0    2 09:03 pts/9    00:00:00 irb 

      

I'm guessing the other thread is meant to run in a background ruby ​​ruby, possibly a parallel distributor / garage manifold.

+1


source







All Articles