We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,477 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Threads

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

1
Contributor
0
Replies
1
View
gisek
Light Poster
26 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page generated in 0.4993 seconds using 2.49MB