ooransoy
ooransoy

Reputation: 797

puts only runs once in a thread/loop

I was making an arcade game in ruby called 'Pushback', where you push every number back to zero, and the objective of the game is to not let any of the numbers exceed 9. But... there is a problem with the refreshing of the screen, where the screen-outputting thread only gives the start state (000) and does not output anything other than that.

The code is here:

$screen = '000'
Thread.new do
  loop do
    puts $screen
    sleep 1
    $screen[0] = ($screen[0].to_i + 1).to_s
    $screen[1] = ($screen[1].to_i + 1).to_s
    $screen[2] = ($screen[2].to_i + 1).to_s
    clear
  end
end
loop do
  case gets.chomp.downcase
  when ?l
    $screen[0] = '0'
  when ?m
    $screen[1] = '0'
  when ?r
    $screen[2] = '0'
  end
end

EDITS:

(1) I have tried making a function outside the thread, then calling it from the inside, but that still doesn't work.

(2) One of the answers is about Mutex. I used it and it worked. Here is the final code

https://gist.github.com/nolcay/c6572089c8292331e2f3

Upvotes: 1

Views: 110

Answers (1)

LukeS
LukeS

Reputation: 481

I would recommend to use a mutex to lock your $screen variable when using it.

You can see here a good Ruby multi-threading explanation.

Upvotes: 2

Related Questions