나는 N 번 호출해야하는 함수가있다. T 스레드가 병렬로 함수를 실행하기를 원합니다. 어떻게 이것을 파이썬으로 모델링 하시겠습니까?Python Threading with a Counter
답변
그리고 지금, 일부 다른 재미 :)에 대한
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]
for t in threadpool:
t.execute(function)
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)
OP는 구현이 아닌 모델을 요구했습니다. 또한 자주 객체를 추가 및 제거하는 경우 deque 사용을 고려할 수 있습니다. – theheadofabroom
파이썬의 문제는 없습니다 때문에 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])
하지만 파이썬에서 스레딩은 가벼운 프로세스가 아니라 논리적 스레드로 의도됩니다. 진정한 동시성 (cuncurrency)을 위해 중량이 많은 쓰레드 (프로세스)를 사용할 수는 있지만 상태를 공유하지는 않습니다. 그 이유는 다른 언어에서는이 중간계가 종종 만병 통치약으로 간주되어 모든 버그의 출처로 선택되기 때문입니다. – theheadofabroom
- 1. Python Threading
- 2. pygtk treestore (Python)에 Counter() 목록 추가하기
- 3. VBScript threading
- 4. POSIX threading on ios
- 5. OpenGl with Python
- 6. Python : FTP with TarFile
- 7. twitter retweets with Python
- 8. python 3.1 with pydev
- 9. NI CVI with Python
- 10. Python String with HTML/
- 11. Open File With Python
- 12. Windows hook with Python
- 13. Env.js with Python 사용
- 14. Mimic Haskell with Python
- 15. Sproutcore with Python Scipy
- 16. 정확히 a <a href> hyperlink with a variable
- 17. Iphone Open With a UIWebView
- 18. Reloadably Return-Path with Python
- 19. $ PYTHONSTARTUP with python 2.7 및 python 3.2
- 20. IE counter-progress (CSS)
- 21. jQuery counter question
- 22. php form submit counter
- 23. 간단한 jquery second counter
- 24. Counter ++ in Parallel.ForEach
- 25. Python : threading + lock이 내 응용 프로그램을 상당히 느리게 만듭니다.
- 26. MS Chart Scaleview & Threading
- 27. Emacs with Python 사용 방법
- 28. Corba with Python 사용 방법
- 29. HTTP 배너 Grabbing with Python
- 30. virtualenv with all Python libraries
N 시간은 어디서 오는가? –
스레드 풀을 만들 때 – theheadofabroom
@BiggAl @fabrizio 파이썬에 내장 된 스레드 풀 개념이 없으므로 추가 정보 없이는 유용하지 않습니다. –