gisek 0 Light Poster

Hi,

I encountered a problem with threads in ruby. I created such a script:

require 'thread'

def func
  $i = 0
  while true
    $i += 1
    $file.write("bbbb\n")
    Thread.pass
  end
end

def func2
  $j = 0
  while true
    $j += 3
    $file.write("aaaa\n")
    Thread.pass
  end
end

def funcTerm
  while true
    a = gets
    if a != ""
      $t1.exit
      $t3.exit
      $t5.exit
    end
  end
end

$file = File.new("out.txt", "w")

$t1 = Thread.new{func}
$t3 = Thread.new{func2}
$t5 = Thread.new{funcTerm}
$t1.join
$t3.join
$t5.join

puts ":"
puts $i
puts ":----:"
puts $j

puts "finished"

It's supposed to start 3 different threads. Thread $t1 appends "bbbb" to a file, thread $t3 appends "aaaa" to the same file. $t5 terminates all threads when input is detected.
Moreover threads do some operations on variables $i and $j, but it's not important here.

The result should be a file (out.txt) filed like that:

bbbb
aaaa
bbbb
aaaa

"bbbb" line should be followed by "aaaa" line and so on. "aaaa" should never be a neighbour of "bbbb". Unfortunately it turns out that sometimes (quite often) it happens. It looks to me like the method Thread.pass isn't working correctly. How to fix it?

Of course I know that in this case threads are unnecessary. I'm just tying to understand the issue of threads. :)

Bye