본문 바로가기

내일배움 캠프/TIL

2023 04 12 python thread,process

python에서 스레드랑 프로세스는 모두 여러작업을동시에 처리하는 다중작업을 위해서 사용하는 방법입니다

 

 

스레드

스레드는 프로세스 내에서 프로세스 자원을 공유하며 작동을 하기때문에 때문에 가볍고 생성및 제거 시간이 짧다는 특징이 있습니다 

이 같은 프로세스 내에서 실행을 하기떄문에 PID(Process ID) 는 전부 같은 값이 나오고 thread id값은 서로 다르게 나오게 됩니다

import threading
import os

def foo():
    print('This is foo')
    print('process id', os.getpid())
 
def bar():
    print('This is bar')
    print('process id', os.getpid())
 
def baz():
    print('This is baz')
    print('process id', os.getpid())

if __name__ == '__main__':
    print('process id', os.getpid())
    thread1 = threading.Thread(target=foo).start()
    thread2 = threading.Thread(target=bar).start()
    thread3 = threading.Thread(target=baz).start()

이렇게 스레드들이 각기 다른 작업을 해도 하나의 프로세스를 공유하고있기때문에 PID는 같게 나온다는 것을 알수있습니다

 

프로세스

프로세스는 운영체제에서 실행 중인 하나의 프로그램을 의미합니다.

각각의 프로세스는 스레드와는 다르게 독립적인 메모리 공간을 가진다는 특징이있습니다

그렇기 때문에 위에있던 스레드와는 다르게

from multiprocessing import Process
import os

def foo():
    print('child process', os.getpid())
    print('my parent is', os.getppid())
  
if __name__ == '__main__':
    print('parent process', os.getpid())

    child1 = Process(target=foo).start()
    child2 = Process(target=foo).start()
    child3 = Process(target=foo).start()

이런식으로 같은 함수를 프로세스 형식으로 실행하게되면 서로  parent process는 같지만 자기자신의 pis값은 다르게 나오기떄문에 각각의 메모리 공간을 가지게된다는특성을 이해 할수 있었습니다