[TxMt] errant rubymate output when dealing with threads

Allan Odgaard throw-away-1 at macromates.com
Sun Nov 19 02:55:06 UTC 2006


On 19. Nov 2006, at 02:23, jeanpierre at gmail.com wrote:

> i am seeing some strange rubymate output when working with threads -
> at times text is not printed on separate lines (when using puts rather
> than print) and at others, the text is not printed at all. any
> suggestions to resolve the rubymate behavior or pointers to where i
> could?

When you do Thread.new there is no guarantee that the code in your  
thread is executed *before* the code after the thread block.

So in your second example, it doesn’t get to run any of the thread  
code, before it reaches the end of your program. Try e.g. put ‘sleep  
1’ before Thread.kill, and you will get output.

Likewise, there is no guarantee that there won’t be a thread schedule  
basically anytime, in the case of puts, the puts call itself is not  
atomic, it writes first the string, then the newline. The reason why  
you see different behavior from RubyMate is that it makes STDOUT non- 
buffered, thus slower, and likely that is why you do see a thread  
switch before it writes the newline, and you don’t see it normally.

If you want to enforce a certain order, you need to introduce locks  
(see Mutex).

For example try to add this to the top of your first example, to make  
puts atomic:

     require "thread"

     $mutex = Mutex.new
     def puts(str)
       $mutex.synchronize { $stdout.puts str }
     end





More information about the textmate mailing list