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?

Answers


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.


Need Your Help

Escaped string of bytes to bytestring

python string byte

I'm new to Python and I need to read bytestring from a command line argument. I'm using Python 3.4.

AlertViewController - whose view is not in the window hierarchy Issue

ios uialertview

In the following code, I am trying to call the method handleEvent only once a particular event takes place. For this, I post a notification where the event occurs (not shown in code below) , so tha...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.