[Python] 쓰레드 Thread 사용하는 방법
2021. 6. 28. 08:34ㆍPython
반응형
[ 우선 따라해보는 Python ]
https://github.com/Mr-DooSun/python-thread
가끔 프로젝트를 진행하다보면 두가지의 함수를 같이 동작 시키고 싶을때 있습니다
그럴땐 Thread를 이용하면 두가지 이상의 함수를 동시에 동작을 시킬수있습니다.
우선 thread를 이용하기 위해선 threading을 추가해줍니다
import threading
그리곤 thread를 돌릴 함수를 만든후 아래 소스에 함수를 돌려줍니다
Tip) daemon thread를 이용 해줄경우 프로그램이 종료시에 thread도 함께 종료 됩니다
※ 하지만 daemon thread를 이용하지 않을경우 프로그램이 종료 하여도 thread는 계속 동작 합니다
thread=threading.Thread(target=test_function) #thread를 동작시킬 함수를 target 에 대입해줍니다
thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
thread.start() #thread를 시작합니다
[ 테스트 소스 ]
import threading
from time import sleep
def hello_1():
while True:
print("1")
sleep(1)
def hello_2():
while True:
print("2")
sleep(1)
def hello_1_thread():
thread=threading.Thread(target=hello_1) #thread를 동작시킬 함수를 target 에 대입해줍니다
thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
thread.start() #thread를 시작합니다
if __name__ == "__main__":
hello_1_thread()
hello_2()
[ 결과 ]
1
2
1
2
....
이상 포스팅을 마치도록 하겠습니다
[완성된 코드]
https://github.com/Mr-DooSun/python-thread
반응형
'Python' 카테고리의 다른 글
[Python] Pyinstaller를 이용하여 py 파일 exe 실행 파일로 변환 (.py to .exe) (5) | 2021.06.28 |
---|---|
[Python] keyboard control, 키보드 제어하는 방법 [pynput-keyboard] (0) | 2021.06.28 |
[Python] mouse control, 마우스 제어 하는 방법 [pynput-mouse] (0) | 2021.06.28 |
[Python] 날씨 정보 api, Darksky forecastio api 사용하는방법 [forecastio] (2) | 2021.06.28 |
[Python] 날짜&시간 모듈 사용 [datetime module] (0) | 2021.06.28 |