2017-04-26 1 views
4

동일한 함수를이라고하는 별도의 스레드에서 호출하고 각 인스턴스에 대해 반환 값이 별도로있는 별도의 목록을 함수없이 복제하는 가장 좋은 방법은 무엇입니까?파이썬에서 별도의 스레드에서 같은 함수를 호출하는 가장 좋은 방법은 무엇입니까?

예 :

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 

편집 : 내가 사용하는 것을 언급하는 것을 잊었다 파이썬 2.7

+0

가능한 복제 [파이썬에서 스레딩을 사용하는 방법?] (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

왜 다중 처리 .Pool 클래스 대신 ThreadPool을 사용하게 될까요? – rbs

+1

@rbs ThreadPool은'IO' 관련 작업을 수행하는 경우 비교적 쉽고 저렴 한'threads'를 시작할 것입니다. 만약'multiprocess'를 사용한다면 오버 헤드가있는'Processes'가 시작될 것입니다. 'threads' else'processes' – vks

0

여기서 ProcessPool은 메모리 집약적 인 작업에 가장 적합한 네트워크 I/O 문제에 가장 적합하기 때문에 ProcessPool은 더 적합합니다. 당신이 threading 주장하는 경우

from concurrent.futures import ProcessPoolExecutor 

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

, 당신은 이런 식으로 할 수 있습니다

  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. 또는 t1, t2 등을 사용 ..

    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 
    
관련 문제