산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python으로 스레드 간 통신 마스터하기:동기화 및 데이터 공유

스레드 간 통신은 Python 다중 스레드 프로그램 내에서 스레드 간의 통신 및 동기화를 활성화하는 프로세스를 의미합니다.

일반적으로 Python의 스레드는 프로세스 내에서 동일한 메모리 공간을 공유하므로 스레드 모듈에서 제공하는 공유 변수, 객체 및 특수 동기화 메커니즘을 통해 데이터를 교환하고 활동을 조정할 수 있습니다.

스레드 간 통신을 용이하게 하기 위해 스레딩 모듈은 잠금, 이벤트, 조건 및 세마포 개체와 같은 다양한 동기화 기본 요소를 제공합니다. 이 튜토리얼에서는 다중 스레드 프로그램의 스레드 간 통신을 제공하기 위해 이벤트 및 조건 개체를 사용하는 방법을 배웁니다.

이벤트 객체

Event 객체는 스레드가 기다리거나 설정할 수 있도록 내부 플래그의 상태를 관리합니다. 이벤트 객체는 이 플래그의 상태를 제어하는 메서드를 제공하여 스레드가 공유 조건에 따라 활동을 동기화할 수 있도록 합니다.

플래그는 처음에는 false이며 set() 메서드를 사용하면 true가 되고,clear() 메서드를 사용하면 false로 재설정됩니다. wait() 메소드는 플래그가 true가 될 때까지 차단됩니다.

다음은 Event 객체의 주요 메소드입니다.

다음 코드는 녹색 또는 빨간색의 교통 신호 상태에 따라 제어되는 교통 흐름을 시뮬레이션하려고 시도합니다.

프로그램에는 두 가지 다른 기능을 대상으로 하는 두 개의 스레드가 있습니다. signal_state() 함수는 신호가 GREEN에서 RED로 변경되는 이벤트를 주기적으로 설정하고 재설정합니다.

Traffic_flow() 함수는 이벤트가 설정될 때까지 기다렸다가 설정이 유지될 때까지 루프를 실행합니다.

from threading import Event, Thread
import time
terminate = False
def signal_state():
 global terminate
 while not terminate:
 time.sleep(0.5)
 print("Traffic Police Giving GREEN Signal")
 event.set()
 time.sleep(1)
 print("Traffic Police Giving RED Signal")
 event.clear()
def traffic_flow():
 global terminate
 num = 0
 while num < 10 and not terminate:
 print("Waiting for GREEN Signal")
 event.wait()
 print("GREEN Signal ... Traffic can move")
 while event.is_set() and not terminate:
 num += 1
 print("Vehicle No:", num," Crossing the Signal")
 time.sleep(1)
 print("RED Signal ... Traffic has to wait")
event = Event()
t1 = Thread(target=signal_state)
t2 = Thread(target=traffic_flow)
t1.start()
t2.start()
# Terminate the threads after some time
time.sleep(5)
terminate = True
# join all threads to complete
t1.join()
t2.join()
print("Exiting Main Thread")

출력

위의 코드를 실행하면 다음과 같은 결과가 출력됩니다 -

Waiting for GREEN Signal
Traffic Police Giving GREEN Signal
GREEN Signal ... Traffic can move
Vehicle No: 1 Crossing the Signal
Traffic Police Giving RED Signal
RED Signal ... Traffic has to wait
Waiting for GREEN Signal
Traffic Police Giving GREEN Signal
GREEN Signal ... Traffic can move
Vehicle No: 2 Crossing the Signal
Vehicle No: 3 Crossing the Signal
Traffic Police Giving RED Signal
Traffic Police Giving GREEN Signal
Vehicle No: 4 Crossing the Signal
Traffic Police Giving RED Signal
RED Signal ... Traffic has to wait
Traffic Police Giving GREEN Signal
Traffic Police Giving RED Signal
Exiting Main Thread

조건 객체

Python 스레딩 모듈의 Condition 개체는 더욱 발전된 동기화 메커니즘을 제공합니다. 스레드가 진행하기 전에 다른 스레드의 알림을 기다릴 수 있습니다. Condition 개체는 항상 잠금과 연결되어 있으며 스레드 간 신호 전달을 위한 메커니즘을 제공합니다.

다음은 threading.Condition() 클래스의 구문입니다 -

threading.Condition(lock=None)

Condition 객체의 주요 메소드는 다음과 같습니다 -

이 예제는 Python 스레딩 모듈의 Condition 객체를 사용하는 간단한 형태의 스레드 간 통신을 보여줍니다. 여기서 thread_a와 thread_b는 Condition 개체를 사용하여 전달되며, thread_a는 thread_b로부터 알림을 받을 때까지 기다립니다. thread_b는 thread_a에게 알리기 전에 2초 동안 대기한 후 완료됩니다.

from threading import Condition, Thread
import time
c = Condition()
def thread_a():
 print("Thread A started")
 with c:
 print("Thread A waiting for permission...")
 c.wait()
 print("Thread A got permission!")
 print("Thread A finished")
def thread_b():
 print("Thread B started")
 with c:
 time.sleep(2)
 print("Notifying Thread A...")
 c.notify()
 print("Thread B finished")
Thread(target=thread_a).start()
Thread(target=thread_b).start()

출력

위의 코드를 실행하면 다음과 같은 결과가 출력됩니다 -

Thread A started
Thread A waiting for permission...
Thread B started
Notifying Thread A...
Thread B finished
Thread A got permission!
Thread A finished

다음은 스레드 간 통신을 제공하기 위해 Condition 개체를 사용하는 방법을 보여주는 또 다른 코드입니다. 여기서 스레드 t2는 taskB() 함수를 실행하고 스레드 t1은 taskA() 함수를 실행합니다. t1 스레드는 조건을 획득하고 이를 알립니다.

그때까지 t2 스레드는 대기 상태에 있습니다. 조건이 해제된 후 대기 스레드는 알림 기능에 의해 생성된 난수를 소비하기 시작합니다.

from threading import Condition, Thread
import time
import random
numbers = []
def taskA(c):
 for _ in range(5):
 with c:
 num = random.randint(1, 10)
 print("Generated random number:", num)
 numbers.append(num)
 print("Notification issued")
 c.notify()
 time.sleep(0.3)
def taskB(c):
 for i in range(5):
 with c:
 print("waiting for update")
 while not numbers: 
 c.wait()
 print("Obtained random number", numbers.pop())
 time.sleep(0.3)
c = Condition()
t1 = Thread(target=taskB, args=(c,))
t2 = Thread(target=taskA, args=(c,))
t1.start()
t2.start()
t1.join()
t2.join()
print("Done")

이 코드를 실행하면 다음과 같은 출력이 생성됩니다.

waiting for update
Generated random number: 2
Notification issued
Obtained random number 2
Generated random number: 5
Notification issued
waiting for update
Obtained random number 5
Generated random number: 1
Notification issued
waiting for update
Obtained random number 1
Generated random number: 9
Notification issued
waiting for update
Obtained random number 9
Generated random number: 2
Notification issued
waiting for update
Obtained random number 2
Done

python

  1. 파이썬 if...else 문
  2. 파이썬 - GUI 프로그래밍 (Tkinter)
  3. Python - 다중 스레드 프로그래밍
  4. Python 문, 들여쓰기 및 주석
  5. 파이썬 전역 키워드
  6. 파이썬 숫자, 유형 변환 및 수학
  7. 파이썬 - 객체 지향
  8. 파이썬 반복자
  9. 코드에서 Python 버전 확인:최소 요구 사항
  10. 예제를 사용하여 Python에서 모듈 가져오기