2011-03-17 5 views
1

나는 N 번 호출해야하는 함수가있다. T 스레드가 병렬로 함수를 실행하기를 원합니다. 어떻게 이것을 파이썬으로 모델링 하시겠습니까?Python Threading with a Counter

답변

3

그리고 지금, 일부 다른 재미 :)에 대한

import threading 
from itertools import repeat 
from multiprocessing.pool import ThreadPool # this is a THREAD POOL! undocumented :) 


def execute_me(): 
    print threading.current_thread().name, 'python is fun' 


tp = ThreadPool(processes=4) 
print tp.map(lambda x: x(), repeat(execute_me, 4)) 

출력 :

% python mpthreadpool.py 
Thread-1 python is fun 
Thread-2 python is fun 
Thread-3 python is fun 
Thread-3 python is fun 
[None, None, None, None] 
0
for t in threadpool: 
    t.execute(function) 
+0

N 시간은 어디서 오는가? –

+0

스레드 풀을 만들 때 – theheadofabroom

+1

@BiggAl @fabrizio 파이썬에 내장 된 스레드 풀 개념이 없으므로 추가 정보 없이는 유용하지 않습니다. –

1
threads = [] 
for i in range(NUM_THREADS): 
    t = threading.Thread(target=your_function, args=your_argslist) 
    t.start() # if you want to start it immediately, otherwise you can defer it 
    threads.append(t) 
+0

OP는 구현이 아닌 모델을 요구했습니다. 또한 자주 객체를 추가 및 제거하는 경우 deque 사용을 고려할 수 있습니다. – theheadofabroom

1

파이썬의 문제는 없습니다 때문에 OS 기반의 쓰레드를 지원한다는 것입니다 유명한 GIL (http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/ 참조). 필자의 의견으로는 실제 스레드 (예 : n 개의 스레드)를 사용하는 가장 쉬운 방법은 평행 한 파이썬 (http://honeypot.net/yet-another-python-ko)에 대한 병렬 맵 버전과 함께 병렬 파이썬 (http://www.parallelpython.com/ 참조) 지도). 다음과 같이 사용할 수 있습니다.

def func(arg1): 
    # do something with arg1 
    return result 

import pp 
import ppmap 

ppmap.ppmap(n, func, [test1, ... test2]) 
+0

하지만 파이썬에서 스레딩은 가벼운 프로세스가 아니라 논리적 스레드로 의도됩니다. 진정한 동시성 (cuncurrency)을 위해 중량이 많은 쓰레드 (프로세스)를 사용할 수는 있지만 상태를 공유하지는 않습니다. 그 이유는 다른 언어에서는이 중간계가 종종 만병 통치약으로 간주되어 모든 버그의 출처로 선택되기 때문입니다. – theheadofabroom