0

私は非同期スレッドマネージャーを実装していて、スレッドへの参照を渡したいのですが、そこで彼の作業の結果を保存する必要があります。そして、すべてのスレッドが終了したら、すべての結果を処理します。

私が必要としているのは、「参照」の操作方法を知ることです。

変数result(またはhash[:result1])があると仮定して、次のようにスレッドに渡します

def test_func
 return 777;
end

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

そして私が欲しいのは次の結果を得ることです

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

コードを機能させるには、コードを何に変更する必要がありますか?

Rubyのバージョンは1.9.3です

4

1 に答える 1

1

ハッシュ全体を関数に渡すことができます:

def test_func
  return 777;
end

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

次に、これは機能します:

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

また、計算が終了した後に確実に結果を取得したい場合は、次のようにスレッドを待機する必要があります。

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

編集:追加されたキー、結合

于 2013-02-28T10:59:43.560 に答える