2

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

0

1 Answer 1

3

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.