-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy_ad_3_7.py
More file actions
80 lines (54 loc) · 1.65 KB
/
py_ad_3_7.py
File metadata and controls
80 lines (54 loc) · 1.65 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Section 3
Concurrency, CPU Bound vs I/O Bound - CPU Bound(2) - Multiprocessing
Keyword - CPU Bound,
"""
# CPU-Bound Multiprocessing 예제(https://realpython.com/python-concurrency/#synchronous-version)
from multiprocessing import current_process, Array, freeze_support, Process, Manager
import time
import os
# 실행함수(계산)
def cpu_bound(number, total_list):
process_id = os.getpid()
process_name = current_process().name
# Process 정보 출력
print(f"Process ID: {process_id}, Process Name: {process_name}")
total_list.append(sum(i * i for i in range(number)))
def main():
# 계산 값
numbers = [3_000_000 + x for x in range(30)]
# 확인
# print(numbers)
# 프로세스 리스트 선언
processes = list()
# 프로세스 공유 매니저
manager = Manager()
# 리스트 획득(프로세스 공유)
total_list = manager.list()
# 실행시간 측정
start_time = time.time()
# 프로세스 생성 및 실행
for i in numbers: # 1 ~ 100 적절히 조절
# 생성
t = Process(name=str(i), target=cpu_bound, args=(i,total_list,))
# 배열에 담기
processes.append(t)
# 시작
t.start()
# Join
for process in processes:
process.join()
print()
# 결과 출력
print(f"Total list : {total_list}")
print(f"Sum : {sum(total_list)}")
# 실행 시간 종료
duration = time.time() - start_time
print()
# 수행 시간
print(f"Duration : {duration} seconds")
if __name__ == "__main__":
# 윈도우 예외시
# freeze_support()
# 메인 함수 실행
main()