2011-07-05 36 views
2

當我運行一個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。

回答

3

sleep()函數在單獨的線程中執行。 Ruby在初始化線程中總是啓動兩個線程。

$ 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 [email protected]@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 

您可以通過使用strace的和gdb獲取更多信息