Ruby threads and the system call

V

Vincent Fourmond

--------------090005050106010103080805
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit


Hello !

I've recently had quite a fair bit of trouble with Ruby threads (on a
Linux box). I wrote three different programs (attached) that write
numbers from within threads:

* one with a standard puts
* one with a system "echo ..."
* one with a fork do system "echo ..." end

The first one behaves as expected (although the numbers are perfectly
ordered, which looks suspicious). In the second one, ruby never manages
to make a second system call in a thread (and finishes before the
subprograms are terminated). The third behaves a little better, but
crashes after, say, 3 to 4 system calls in a thread...

Is this true on other boxes ? Is it a flaw of my understanding of
threads, or a limitation inherent to the way threads are coded in Ruby ?
If that is so, it's really annoying - no way to delegate heavy tasks to
other well-written programs...

Thoughts ?

Vince

--------------090005050106010103080805
Content-Type: text/plain;
name="test_threads_no_system.rb"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="test_threads_no_system.rb"

#!/usr/bin/ruby

10.times do |i|
Thread.start(i) do |i|
10.times do |j|
puts "#{i}.#{j}"
end
end
end


--------------090005050106010103080805
Content-Type: text/plain;
name="test_threads_system.rb"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="test_threads_system.rb"

#!/usr/bin/ruby

10.times do |i|
Thread.start(i) do |i|
10.times do |j|
system "echo #{i}.#{j} "
end
end
end


--------------090005050106010103080805
Content-Type: text/plain;
name="test_threads_system_fork.rb"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="test_threads_system_fork.rb"

#!/usr/bin/ruby

10.times do |i|
Thread.start(i) do |i|
10.times do |j|
fork do
system "echo #{i}.#{j} "
end
end
end
end


--------------090005050106010103080805--
 
V

Vincent Fourmond

Hello !
10.times { |i|
x = Thread.new(i) {
10.times { |j|
fork {
system "echo #{i}, #{j} >> temp.txt"
}
Process::wait
}
}
x.join

Great thanks, I had completely forgotten to call join for the
threads... By the way, the version with fork is around 4 times faster on
my box:

ruby test_threads_system.rb > /dev/null 0.04s user 0.10s system 21% cpu
0.639 total
ruby test_threads_system_fork.rb > /dev/null 0.00s user 0.04s system
25% cpu 0.171 total

Cheers and thanks !!

Vince
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,017
Latest member
GreenAcreCBDGummiesReview

Latest Threads

Top