Reputation: 11331
I am working on a multi-threading program in Ruby, just want to make sure a simple question.
For example I have a class called School
, and two other classes are Boy
and Girl
.
In School
I have a hash that keeps track all boys and girls attendance. And I make each boy/girl a thread in School
(so that they can have activity individually)
I want all boys and girls threads can see and make change to the attendance hash. (like if a girl comes to school, check her name in the hash, when she leaves, delete her name in the hash)
I know I can use monitor to do a thread lock, but I dont familiar with scripting language so I am not sure how all threads can see the hash variable and modify them. (kind of like static in C/JAVA)
Thank you
Upvotes: 2
Views: 573
Reputation: 4843
Something like this :
threads = []
hash = {g:0,n:0}
m = Mutex.new
threads << Thread.new(optional_pass_by_value) do |value|
#do whatever
#modify hash
m.synchronize {hash[:g] += 1} #By using synchronize you get an atomic behavior
#Only one thread will be able to access and modify this hash at one time.
end
threads.each {|t| t.join}
Upvotes: 3