본문 바로가기
PRACTICE/Basic

[Python] 프로세스, 스레드 조작

by 1005 2025. 3. 14.

* 부모 프로세스, 자식 프로세스 관계 PID로 확인

1
2
3
4
5
6
7
8
9
10
11
12
from multiprocessing import Process
import os
 
def foo():
    print('foo: child process: ', os.getpid())
    print('foo: parent process: ', 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()

 

 

* 멀티 프로세스 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from multiprocessing import Process
import os
 
# 기능 별 각기 다른 프로세스 생성
def aoo():
    print('aoo executed!!'# 입력 기능
 
def boo():
    print('boo executed!!'# 출력 기능
 
def coo():
    print('coo executed!!'# 검사 기능
 
if __name__ == '__main__':
    print('parent process', os.getpid())
    child1 = Process(target=aoo).start()
    child2 = Process(target=boo).start()
    child3 = Process(target=coo).start()

 

 


* 동일한 프로세스에서 파생된 여러 스레드

1
2
3
4
5
6
7
8
9
10
11
12
import threading
import os
 
def foo():
    print('foo: my thread id is: ', threading.get_native_id()) # thread id print
    print('foo: my pid is: ', os.getpid()) # process id print
 
if __name__ == '__main__':
    print('my pid is: ', os.getpid())
    thread1 = threading.Thread(target=foo).start()
    thread2 = threading.Thread(target=foo).start()
    thread3 = threading.Thread(target=foo).start()

pid는 동일하지만 스레드 id는 다 다름.

 

 

* 멀티 스레드 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import threading
import os
 
def aoo():
    print('aoo executed!!'# 입력 기능
 
def boo():
    print('boo executed!!'# 출력 기능
 
def coo():
    print('coo executed!!'# 검사 기능
 
if __name__ == '__main__':
    print('my pid is: ', os.getpid())
    thread1 = threading.Thread(target=aoo).start()
    thread2 = threading.Thread(target=boo).start()
    thread3 = threading.Thread(target=coo).start()

 

댓글