Ph0en1x
Ph0en1x

Reputation: 10087

change value by reference in ruby

I implemeting async thread manager and I want to pass reference to thread, where it should save the results of his work. And then when all thread finished i will handle all results.

What I need is to know how to work with 'references'.

lets assume I have variable result (or hash[:result1]), I want to pass it to the thread like

def test_func
 return 777;
end

def thread_start(result)
 Thread.new do
  result = test_func;
 end
end

and I want is to get following result

result = 555
thread_start(result);
#thread_wait_logic_there
result == 777; #=> true

hash = {:res1 => 555};
thread_start(hash[:res1])
#thread_wait_logic_there
hash[:res1]==777 #=> true

what should I chnage in my code to make it work?

Ruby version is 1.9.3

Upvotes: 0

Views: 58

Answers (1)

valodzka
valodzka

Reputation: 5805

You can pass entrire hash to function:

def test_func
  return 777;
end

def thread_start(hash, key)
  Thread.new do
    hash[key] = test_func;
  end
end

Then this will work:

hash = {:res1 => 555};
thread_start(hash, :res1)
hash[:res1]==777 #=> true

Also if you want to be sure that you getting result after computations finished you must wait for thread, like this:

hash = {:res1 => 555};
thread_start(hash, :res1).join
hash[:res1]==777 #=> true

Edit: Added key,join

Upvotes: 1

Related Questions