예시로 알아보는 Python Heap Memory

프로세스 메모리는 크게 code, data, stack, heap 영역이 있는데 이번 글에서는 stack, heap 영역을 다룰 예정이다

그럼 heap 영역은 왜 알아야 할까?

  1. 파이썬은 모든 게 객체이기 때문, 즉 값을 heap에 저장하고 stack에서 참조한다
  2. 모든 thread는 자기 process heap memory 영역을 공유한다 이걸 이용해서 좀 더 유연한 프로세스를 만들 수 있다
  3. 객체를 무분별하게 생성하지 않기 위해서
  4. 버그를 찾기 위해
  5. 기타 등등…

간단하게 예시를 들면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from threading import Thread
from time import sleep

detect_word = 'dog'

# 문장에 탐지 단어가 있는지 확인하는 함수
def print_worker():
global detect_word
text = 'dogs are cute'
while 1:
check = detect_word in text
print(check)
if check is False:
break
sleep(1)

# 탐지 단어를 바꾸는 함수
def change_worker():
global detect_word
sleep(3)
detect_word = 'cat'


tread1 = Thread(target=print_worker)
tread1.start()

tread2 = Thread(target=change_worker)
tread2.start()
실행 결과는 
True
True
True
False

heap 메모리 그림을 보면 프로세스 실행 3초 뒤
thread2가 detect_word를 cat으로 바꾸었기 때문에
heap 메모리를 공유하는 thread1의 detect_word도 cat을 가리키고 있다
dog는 reference counting이 0이 되어 GC에 의해 메모리 해제된다

간단한 예시지만 이런 특징을 사용해서 좀 더 유연한 프로그램을 만들 수 있다
thread 프로그래밍이 장점이 많지만 메모리를 공유하기 때문에 연산 작업할 때는 lock을 사용하여 thread-safe하게 신경 써야 한다
하지만 lock은 처리 시간을 느리게 하므로 주의가 필요하다

예시로 알아보는 Python Heap Memory

http://hyunsuk2.github.io/2021/02/27/python-heap-memory/

Author

HyunSuk

Posted on

2021-02-27

Updated on

2023-12-23

Licensed under

댓글