Thanks for all the fish
Thanks for all the fish

Reputation: 1701

Ruby - Why Thread doesn't respect method put?

The following code throw messages without putting them with line break.

threads = []
counter = 1000
counter.times do
     threads << Thread.new do 
        puts "This is a line."
        sleep 1
     end
end

threads.each {|t| t.join}

The result is

This is a line. This is a line

This is a line.
This is a line.

and so on...

Is there anyway to print the result line in a tidier way?

Upvotes: 0

Views: 117

Answers (1)

willglynn
willglynn

Reputation: 11520

puts works internally by printing its argument, then by printing a newline. Sometimes, the thread gets interrupted between the two operations, resulting in the behavior you're seeing. You could instead say:

 print "This is a line.\n"

...which would write the entire string -- including newline -- in a single operation.

Upvotes: 1

Related Questions