2017-04-26 39 views
4

同じファンクションを別々のスレッドで呼び出す方法と、各インスタンスの戻り値を別々のリストにする方法は何ですか?ファンクション別のスレッドで同じ関数を呼び出すPythonの最良の方法は何ですか?

例:

import threading 


def function(a): 

    returned_values = [] 

    ct = threading.currentThread() 
    while getattr(ct, "do_run", True): 
     ret = do_something(a) 
     returned_values.append(ret) 


t1 = threading.Thread(target=function, args=("AAA",)) 
t2 = threading.Thread(target=function, args=("BBB",)) 
t3 = threading.Thread(target=function, args=("CCC",)) 

t1.start() 
t2.start() 
t3.start() 

import time;time.sleep(10) 
t1.do_run = t2.do_run = t3.do_run = False 

編集:私が使用することを言及するのを忘れたのPython 2.7

+0

可能な重複[Pythonでスレッドを使用するには?](http://stackoverflow.com/questions/2846653/how-to-use- threading-in-python) – philshem

答えて

6

使用のThreadPoolこの

from multiprocessing.pool import ThreadPool 

pool = ThreadPool() 
pool.map(function, list_containing_args) 

P.Sよう

何かit works similar to multiprocess map.Each argument is given a new thread .You can specify the number of threads you want to spawn if you have limited resources or a big list

from multiprocessing.pool import ThreadPool 
import subprocess 
def func(ip): 
    c=subprocess.Popen("ping -c 3 "+ip, shell=True, stdout=subprocess.PIPE) 
    output, error= c.communicate() 
    return output 

pool = ThreadPool() 
for i in pool.map(func,["127.0.0.1", "www.google.com", "www.facebook.com"]): 
    print i 
+0

ありがとうございました。これがどのように機能するのか少し説明してください。 – rbs

+0

multiprocessing.Poolクラスの代わりにThreadPoolを使用する理由はありますか? – rbs

+1

@rbs ThreadPoolは 'IO'関連の仕事をしているなら、比較的簡単で安価な' threads'を起動します。 'multiprocess'を使うと、オーバーヘッドを持つ' Processes'が起動します。 'threads' else' processes' – vks

0

ProcessPoolがメモリ集約型タスクに最も適しているネットワークI/Oの問題に最も適しているため、ここではProcessPoolは適していません。

from concurrent.futures import ProcessPoolExecutor 

with futures.ProcessPoolExecutor(max_workers=n) as executor: 
    executor.map(fn, args) 
0

あなたはthreadingを主張した場合、あなたはこのようにそれを行うことがあります。事前

であなたの引数を設定し

  1. n_thread, args_set = 3, [('AAA',), ('BBB',), ('CCC',)] 
    
  2. ショップリスト

    threads = [threading.Thread(target=function, args=args_set[i]) 
          for i in range(n_thread)] 
    [t.start() for t in threads] 
    
    内のすべてのインスタンス
  3. またはt1t2などを使用。..

    for i in range(n_thread): 
        var_thread = locals()['t%d' % i] 
        var_thread = threading.Thread(target=function, args=args_set[i]) 
        var_thread.start() 
    print t1, t2 
    
関連する問題