from threading import Thread from time import sleep
detect_word = 'dog'
# 문장에 탐지 단어가 있는지 확인하는 함수 defprint_worker(): global detect_word text = 'dogs are cute' while1: check = detect_word in text print(check) if check isFalse: break sleep(1)
# 탐지 단어를 바꾸는 함수 defchange_worker(): global detect_word sleep(3) detect_word = 'cat'
heap 메모리 그림을 보면 프로세스 실행 3초 뒤 thread2가 detect_word를 cat으로 바꾸었기 때문에 heap 메모리를 공유하는 thread1의 detect_word도 cat을 가리키고 있다 dog는 reference counting이 0이 되어 GC에 의해 메모리 해제된다
간단한 예시지만 이런 특징을 사용해서 좀 더 유연한 프로그램을 만들 수 있다 thread 프로그래밍이 장점이 많지만 메모리를 공유하기 때문에 연산 작업할 때는 lock을 사용하여 thread-safe하게 신경 써야 한다 하지만 lock은 처리 시간을 느리게 하므로 주의가 필요하다