반응형
나란히 실행할 두 개의 타이머가 있지만이 두 스레드가 서로 상호 작용하도록 만드는 방법을 모르겠습니다. 잠금, 이벤트 또는 모든 것을 전달하십시오.
누군가가 그 기능에 대한 간략한 설명과 함께 여기에 간단한 전체 예제를 덤프 할 수 있습니까?
저는 3.3을 배우려고 노력 중이므로 가능하면이 버전에서 작동하는 코드를 게시 할 수 있습니다. 나는 또한 내가 찾은 튜토리얼이 그들이 어떤 버전의 Python을 시험하고 있는지 알려주지 않는다는 것을 발견했습니다.
해결 방법
#!python3
import threading
from queue import Queue
import time
# lock to serialize console output
lock = threading.Lock()
def do_work(item):
time.sleep(.1) # pretend to do some lengthy work.
# Make sure the whole print completes or threads can mix up output in one line.
with lock:
print(threading.current_thread().name,item)
# The worker thread pulls an item from the queue and processes it
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
# Create the queue and thread pool.
q = Queue()
for i in range(4):
t = threading.Thread(target=worker)
t.daemon = True # thread dies when main thread (only non-daemon thread) exits.
t.start()
# stuff work items on the queue (in this case, just a number).
start = time.perf_counter()
for item in range(20):
q.put(item)
q.join() # block until all tasks are done
# "Work" took .1 seconds per task.
# 20 tasks serially would be 2 seconds.
# With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
print('time:',time.perf_counter() - start)
산출:
Thread-3 2
Thread-1 0
Thread-2 1
Thread-4 3
Thread-3 4
Thread-1 5
Thread-2 6
Thread-4 7
Thread-3 8
Thread-1 9
Thread-2 10
Thread-4 11
Thread-3 12
Thread-1 13
Thread-2 14
Thread-4 15
Thread-1 17
Thread-3 16
Thread-2 18
Thread-4 19
time: 0.5017914706686906
참조 페이지 https://stackoverflow.com/questions/16199793
반응형
'파이썬' 카테고리의 다른 글
파이썬 Django의 ImageField 이미지가 템플릿에로드되지 않습니다. (0) | 2021.01.19 |
---|---|
파이썬 하위 프로세스 호출에서 종료 코드 및 stderr 가져 오기 (0) | 2021.01.19 |
파이썬 numpy 행 합계로 행 나누기 (0) | 2021.01.19 |
파이썬 Map의 키 배열 가져 오기 (0) | 2021.01.19 |
파이썬 파일 모드 "w +"와 혼동 (0) | 2021.01.19 |
댓글