红宝石。两个线程而不是一个

时间:2011-07-05 02:53:43

标签: ruby multithreading

当我运行Ruby程序时,解释器创建两个线程而不是一个。

以下是示例程序:

# example.rb

sleep 60

that是以下命令的工作结果:

watch -ctn1 'ps -T -eo cmd,pid,nlwp,lwp | grep "ruby example.rb" | grep -v "grep"'

为什么Ruby会这样做?

感谢。

Debian GNU / Linux 6.0.1;

Ruby 1.9.2。

1 个答案:

答案 0 :(得分:3)

sleep()函数在单独的线程中执行。 Ruby总是在初始化线程中启动两个线程。

您可以使用strace和gdb获取更多信息:

$ strace -f ruby -e "sleep 1" 2>&1 | less
$ strace -f ruby -e "puts '12'" 2>&1 | less

$ gdb ruby
(gdb) set args -e 'puts "12"'
(gdb) break start_thread
Function "start_thread" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (start_thread) pending.
(gdb) run 
Starting program: /usr/local/rvm/rubies/ruby-1.9.2-p180/bin/ruby -e 'puts "12"'
[Thread debugging using libthread_db enabled]
[New Thread 0xb7b47b70 (LWP 27630)]
[Switching to Thread 0xb7b47b70 (LWP 27630)]

Breakpoint 1, 0xb7dd68b6 in start_thread () from /lib/tls/i686/cmov/libpthread.so.0
(gdb) thread apply all bt

Thread 2 (Thread 0xb7b47b70 (LWP 27630)):
#0  0xb7dd68b6 in start_thread () from /lib/tls/i686/cmov/libpthread.so.0
#1  0xb7cdea4e in clone () from /lib/tls/i686/cmov/libc.so.6

Thread 1 (Thread 0xb7c0f6c0 (LWP 27627)):
#0  0xb7fe2430 in __kernel_vsyscall ()
#1  0xb7ddb015 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/tls/i686/cmov/libpthread.so.0
#2  0xb7f711f1 in native_cond_wait () at thread_pthread.c:127
#3  rb_thread_create_timer_thread () at thread_pthread.c:836
#4  0xb7e669b5 in rb_call_inits () at inits.c:57
#5  0xb7e48d1d in ruby_init () at eval.c:60
#6  0x080487de in main (argc=3, argv=0xbffff834) at main.c:34