아래 코드는 thread 사용의 기본이 되는 코드이다.
# test.py
import threading
import time
def worker(msg):
print(f'{threading.currentThread().getName()} is start : {msg}')
time.sleep(3)
print(f'{threading.currentThread().getName()} is end : {msg}')
def main():
for i in range(10):
msg = f"hello {i}"
th = threading.Thread(target=worker, name=f"[th def {i}]", args=(msg,))
th.start()
if __name__ == "__main__":
main()
thread를 class 형태로 만들수도 있다.
import threading
import time
class Worker(threading.Thread):
def __init__(self, args, name=""):
threading.Thread.__init__(self)
self.name = name
self.args = args
def run(self):
print(f'{self.name} is start : {self.args}')
time.sleep(3)
print(f'{self.name} is end : {self.args}')
def main():
for i in range(10):
msg = f"hello {i}"
th = Worker(args={msg,}, name=f"[th class{i}]")
th.start()
if __name__ == "__main__":
main()
메인 thread가 종료될 때 자신의 실행 상태와 상관없이 종료되는 서브 thread를 의미한다. threading 모듈에서 데몬 thread의 생성은 daemon 속성을 True로 변경하면 된다.
import threading
import time
class Worker(threading.Thread):
def __init__(self, args, name=""):
threading.Thread.__init__(self)
self.name = name
self.args = args
def run(self):
print(f'{self.name} is start : {self.args}')
time.sleep(3)
print(f'{self.name} is end : {self.args}')
def main():
for i in range(10):
msg = f"hello {i}"
th = Worker(args={msg,}, name=f"[th cls{i}]")
th.daemon = True # <<<<<<<<<<<<<< add !!!!
th.start()
if __name__ == "__main__":
main()
main thread에서 sub-thread를 생성을 하면, 각 thread에서 3초 sleep을 한후 print()를 수행하는데, main thread가 바로 종료가 되기 때문에 sub-thread도 바로 종료가 되면서 관련 print() 로그가 출력되지 않는다.
이를 해결하기 위해서 join() 함수를 사용한다.
join()은 thread가 작업을 완료할 때까지 기다리는 것을 의미한다.
import threading
import time
class Worker(threading.Thread):
def __init__(self, args, name=""):
threading.Thread.__init__(self)
self.name = name
self.args = args
def run(self):
print(f'{self.name} is start : {self.args}')
time.sleep(3)
print(f'{self.name} is end : {self.args}')
def main():
print("main thread start")
th = []
for i in range(10):
msg = f"hello {i}"
th.append(Worker(args={msg,}, name=f"[th cls{i}]"))
th[i].daemon = True
th[i].start()
print("main thread end")
for i in range(10):
th[i].join()
print(f'{i} thread joined')
if __name__ == "__main__":
main()
"for i in range(10)" 구문으로 Worker thread를 10개 생성하고 이를 th 리스트에 append로 add한다.
이후 daemon thread를 만들기 위해 "th[i].daemon = True" 를 수행하고, th[i].start() 함수를 사용하여 순차적으로 thread의 run() 함수를 호출한다.
이후 th[i].join() 함수로 각 thread가 종료되기를 기다린 후 종료되는 코드이다.
[파이썬(Python)] #22. for문 / enumerate 내장함수사용 (0) | 2021.08.20 |
---|---|
[파이썬(Python)] #21. 멀티프로세싱 ( multiprocessing ) (0) | 2021.08.20 |
[파이썬(Python)] #16. 문자열/숫자 - 배열 입력받기 (0) | 2021.08.19 |
[파이썬(Python)] #15. List에 map 사용하기 (0) | 2021.08.19 |
[파이썬(Python)] #13. 자료형 (튜플(tuple)) (0) | 2021.08.19 |