파이썬에서 여러 스레드를 동기화합니다
-
23-08-2019 - |
문제
필요한 곳에 문제가 있습니다 x
모두 동기화 지점에 도달 할 때까지 기다릴 스레드. 내 솔루션을 사용합니다 synchronise
아래의 메소드는 동기화해야 할 때 각 스레드 함수에 의해 호출됩니다.
더 좋은 방법이 있습니까?
thread_count = 0
semaphore = threading.Semaphore()
event = threading.Event()
def synchronise(count):
""" All calls to this method will block until the last (count) call is made """
with semaphore:
thread_count += 1
if thread_count == count:
event.set()
event.wait()
def threaded_function():
# Do something
# Block until 4 threads have reached this point
synchronise(4)
# Continue doing something else
해결책
스레드를 동기화하는 방법에는 여러 가지가 있습니다. 많은.
동기화 외에도 다음과 같은 작업을 수행 할 수 있습니다.
작업을 동기화 지점 주변의 두 단계로 나눕니다. 사전 동시 단계를 수행하는 스레드를 시작하십시오. 그런 다음 "조인"을 사용하여 모든 스레드가 끝날 때까지 기다릴 때까지 기다립니다. SYNC 사후 단계를 수행하는 새 스레드를 시작하십시오. 나는 이것을 동기화하는 것을 선호합니다.
대기열을 만듭니다. 동기화 잠금을 획득하십시오. 모든 스레드를 시작하십시오. 각 스레드는 큐에 항목을 넣고 동기화 잠금을 기다립니다. "메인"스레드는 큐의 루프 탈 수용 항목에 있습니다. 모든 스레드가 큐에 항목을 넣으면 "기본"스레드는 동기화 잠금을 방출합니다. 다른 모든 스레드는 이제 다시 자유롭게 실행할 수 있습니다.
여러 가지 IPC (Intervicess Communication) 기술이 있습니다.이 기술은 모두 스레드 동기화에 사용할 수 있습니다.
다른 팁
장벽이 구현되었습니다 Python 3.2
장벽 사용의 예 :
from threading import Barrier, Thread
def get_votes(site):
ballots = conduct_election(site)
all_polls_closed.wait() # do not count until all polls are closed
totals = summarize(ballots)
publish(site, totals)
all_polls_closed = Barrier(len(sites))
for site in sites:
Thread(target=get_votes, args=(site,)).start()
제휴하지 않습니다 StackOverflow