Python_4 - jjin-choi/study_note GitHub Wiki
Β§ Parallel process
https://github.com/imguru-mooc/python_intermediate/tree/master/5.%EB%B3%91%EB%A0%AC%20%EC%B2%98%EB%A6%AC
1. Thread
- from threading import Thread
- Thread() λ thread κ° μ€νν λμμ μ€μ νλ μ½λμ΄λ©° start() μ thread κ° μν
- thread λ₯Ό μ’
λ£μν€κΈ° μν΄μλ flag λ₯Ό μ§μ ν΄μ£Όλ©΄ μ’λ€.
from threading import Thread
import time
class CountdownTask:
def __init__(self):
self._running = True
def terminate(self):
self._running = False
def run(self, n):
while self._running and n > 0:
print("T-minus", n)
n -= 1
time.sleep(5)
c = CountdownTask()
t = Thread(target=c.run, args=(10,))
t.start()
time.sleep(20)
print('About to terminate')
c.terminate()
t.join()
print('Terminated')
- Event() κ°μ²΄ : thread κ° μ μμλμλμ§ νμΈνκ³ μΆμ λ νΉμ thread κ° νΉμ μ§μ μ λλ¬νλμ§ μμμΌ ν κ²½μ°
- evt = Event() λΌκ³ μμ±νλ©΄, μμ±κ³Ό λμμ λ΄λΆ κ°μ΄ 0 μΌλ‘ μ΄κΈ°ν λλ€.
- ν¨μμ args λ‘ evt λ₯Ό μ£Όκ³ ν¨μ λ΄λΆμμ evt.set() μ νλ©΄ Event κ°μ 1 μ΄ λ¨
- λ³λ ¬μ²λ¦¬ νλ λΆλΆμμ evt.wait() λ₯Ό νλ©΄, 1 μ΄ λλ μκ° κ·Έ λΆλΆλ κΈ°λλλ€.
import time
def countdown(n, started_evt):
print("countdown starting")
started_evt.set()
while n > 0:
print("T-minus", n)
n -= 1
time.sleep(5)
started_evt = Event()
print("Launching countdown")
t = Thread(target=countdown, args=(10,started_evt))
t.start()
started_evt.wait()
print("countdown is running")
- νμ§λ§ Event λ ν λ² μ°κΈ°μλ μ’μ§λ§, μ£ΌκΈ°μ μΌλ‘ μ¬μ©νκΈ°μλ μ’μ§ μμ β Condition() μ μ¬μ©νμ !
- Condition μ μ§μκ°λ₯ν νΉμ±μ΄ μκ³ μλμΌλ‘ locking λλ κΈ°λ₯μ΄ μλ€.
import threading
import time
class PeriodicTimer:
def __init__(self, interval):
self._interval = interval
self._flag = 0
self._cv = threading.Condition()
def start(self):
t = threading.Thread(target=self.run)
t.daemon = True
t.start()
def run(self):
while True:
time.sleep(self._interval)
with self._cv:
self._flag ^= 1
self._cv.notify_all()
def wait_for_tick(self):
with self._cv:
last_flag = self._flag
while last_flag == self._flag:
self._cv.wait()
ptimer = PeriodicTimer(5)
ptimer.start()
def countdown(nticks):
while nticks > 0:
ptimer.wait_for_tick()
print("T-minus", nticks)
nticks -= 1
def countup(last):
n = 0
while n < last:
ptimer.wait_for_tick()
print("Counting", n)
n += 1
threading.Thread(target=countdown, args=(10,)).start()
threading.Thread(target=countup, args=(5,)).start()