본문 바로가기

개발

Python Run Thread

728x90

파이썬은 기본적으로 싱글 쓰레드로 동작한다. 따라서, 병렬 처리를 위해서는 threading 모듈을 이용하여 Multi Thread 로 동작 하도록 해야 한다.

 

python 에서 병렬 처리를 하는 방법인인 Thread 는 가볍지만 GIL로 작업은 한번에 하나의 Thread 에서만 동작하므로 CPU 작업이 적고 IO 작업이 많은 경우에 효과적이라고 한다.

 

이런 경우 thread =threading.Thread(target=functionn) 과 같이 thread 를 선언하고 thread.start() 로 시작 하면 된다.

 

아래의 코드는 flask 로 http://localhost:5000 에 접속하면 thread 2개가 실행되면서 randint 로 생성한 숫자(초) 간격으로 randint 함수로 생성한 숫자까지 출력하는 코드이다.

 

import time
import threading
from random import randint
from flask import Flask


def function1():
    for index in range(randint(1, 10)):
        time.sleep(randint(1, 5))
        print("[1] function 1 " + str(index))
    print("----- End function 1 -----")
def function2():
    for index in range(randint(1, 10)):
        time.sleep(randint(1, 5))
        print("[2] function 2 " + str(index))
    print("----- End function 2 -----")


app = Flask(__name__)


@app.route('/')
def hello():
    th1 = threading.Thread(target=function1)
    th2 = threading.Thread(target=function2)

    th1.start()
    th2.start()

    return "Run Thread!!!"


if __name__ == '__main__':
    app.debug = True
    app.run()

 

 

 

 

#TIP
GIL은 Python bytecodes를 실행할 때 여러 thread를 사용할 경우, 단 하나의 thread만이 Python objects에 접근할 수 있도록 제한하는 mutex 이다. 이 잠금장치가 필요한 이유는 CPython의 메모리 관리법이 thread-safe 하지 않기 때문이다. 이렇게 thread-safe 하지 않다고 이야기 한 이유는 Python이 만들어질 시기에는 thread라는 개념이 없었기 때문에 이에 대한 고려가 되지 않았기 때문이다.