Is it 0K to use class variables to communicate with threads in Rails?
Are there any pros or cons compared to using queues?
I’m not sure if this works in any environment, it worked in mine: Ruby Enterprise + Passenger + nginx + Rails 3
Here’s an example:
# rails runner "ThreadJob.new.run"
class ThreadJob
@@counter = 0
def run
producer = Thread.new do
1.upto 10 do
sleep 1
@@counter+= 1
puts "Producer: #{@@counter}"
end
end
consumer = Thread.new do
sleep 0.5
1.upto 10 do
sleep 1
@@counter-= 1
puts "Consumer: #{@@counter}"
end
end
producer.join
consumer.join
puts @@counter # result should be 0
end
end
I’m wondering if this can work if I modify @@counter from within another process.
No, it’s not ok to update class variables from multiple threads like your example.
Take a look at the explanation of why, and how to solve this using the Mutex class:
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html