Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[박산야] W2 Mission 입니다. #36

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
Binary file added missions/.DS_Store
Binary file not shown.
Binary file added missions/W2/.DS_Store
Binary file not shown.
Binary file added missions/W2/M1/.DS_Store
Binary file not shown.
24 changes: 24 additions & 0 deletions missions/W2/M1/M1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import multiprocessing
import time

def work_log(task):
'''
Args:
task(str, int)
'''
name, wait = task
print(f"프로세스 {name}가 {wait}초간 대기")
time.sleep(wait)
print(f"프로세스 {name}가 완료됨.")

tasks = { # task_name : duration(sec)
'A' : 5,
'B' : 2,
'C' : 1,
'D' : 3
}

if __name__ == "__main__":

with multiprocessing.Pool(processes=2) as pool:
pool.map(work_log, list(tasks.items()))
28 changes: 28 additions & 0 deletions missions/W2/M2/M2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import multiprocessing
from multiprocessing import Process

def work_log(task='아시아'):
'''
Args:
task(str)
'''
# print(f"PID Child : {multiprocessing.current_process().pid}")
print(f"Proc Name : {multiprocessing.current_process().name}")
print(f"PID Parent : {multiprocessing.parent_process().pid}")
print(f'대륙의 이름은 : {task}')

tasks = ['아메리카', '유럽', '아프리카']

if __name__ == "__main__":
num_processes = 2

proc1 = Process(target=work_log)
processes = [Process(target=work_log, args=(task, )) for task in tasks]

proc1.start()
for proc in processes:
proc.start()

proc1.join()
for proc in processes:
proc.join()
Binary file added missions/W2/M3/.DS_Store
Binary file not shown.
62 changes: 62 additions & 0 deletions missions/W2/M3/M3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import multiprocessing as mp
from multiprocessing import Process, Queue
# 내 코드 : args가 dict type
def push_work(task:tuple, queue:Queue):
'''
Args:
task (tuple(int, str))
queue (multiprocess.Queue)
'''
num, color = task
print(f'항목 번호: {num} {color}')
# queue.put(f'항목 번호: {num} {color}')
queue.put((num, color))

def pull_work(queue:Queue):
'''
Args:
queue (multiprocess.Queue)
'''
num, color = queue.get()
print(f'항목 번호: {num-1} {color}')

tasks = { # task_name : duration(sec)
1 : '빨간색',
2 : '녹색',
3 : '파란색',
4 : '검정색'
}

colors = ['빨간색', '녹색', '파란색', '검정색']

if __name__ == "__main__":

queue = Queue()
proc_push = [Process(target=push_work, args=(task, queue))for task in tasks.items()]
proc_pull = [Process(target=pull_work, args=(queue,))for _ in range(len(tasks.keys()))]

print("큐에 항목 푸시:")
for push in proc_push:
push.start()
for push in proc_push:
push.join()

print("대기열에서 항목 팝:")
for pull in proc_pull:
pull.start()
for pull in proc_pull:
pull.join()

queue.close()
queue.join_thread()
'''
close()
현재 프로세스가 이 큐에 더는 데이터를 넣지 않을 것을 나타냅니다.
버퍼에 저장된 모든 데이터를 파이프로 플러시 하면 배경 스레드가 종료됩니다.
큐가 가비지 수집될 때 자동으로 호출됩니다.

join_thread()
배경 스레드에 조인합니다.
close() 가 호출된 후에만 사용할 수 있습니다.
배경 스레드가 종료될 때까지 블록해서 버퍼의 모든 데이터가 파이프로 플러시 되었음을 보증합니다.
'''
50 changes: 50 additions & 0 deletions missions/W2/M4/multiprocessing_all_in_one.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from multiprocessing import Process, Queue, Lock, current_process
import queue
import time

def pull_task(pull_q:Queue, push_q:Queue, lock):
while True:

try:
with lock:
num = pull_q.get_nowait()

except queue.Empty as e:
# print(f"Queue is empty: {current_process().name}", e)
break

else:
time.sleep(0.5)
push_q.put(msg := f"Task no {num} is done by {current_process().name}")
# print(f"Push {num} by {current_process().name}")


if __name__ == "__main__":

tasks_to_accomplish = Queue()
tasks_that_are_done = Queue()

lock = Lock()

for i in range(10):
print(f"Task no {i}")
tasks_to_accomplish.put(i)


procs = [Process(target=pull_task, args=(tasks_to_accomplish, tasks_that_are_done, lock))for _ in range(4)]

for proc in procs:
proc.start()

for proc in procs:
proc.join()

while not tasks_that_are_done.empty():
print(tasks_that_are_done.get())

tasks_to_accomplish.close()
tasks_to_accomplish.join_thread()

tasks_that_are_done.close()
tasks_that_are_done.join_thread()

Binary file added missions/W2/M5/.DS_Store
Binary file not shown.
Binary file added missions/W2/M5/D2Coding-Ver1.3.2-20180524.ttf
Binary file not shown.
453 changes: 453 additions & 0 deletions missions/W2/M5/M5.ipynb

Large diffs are not rendered by default.

Loading