Python/Python

[Python] Concurrency Thread Decorator - 3

상쾌한기분 2022. 8. 14. 00:12
728x90
반응형

[Python] Concurrency Thread Decorator

Thread Decorator

정말로 간단한 함수들을 Thread를 사용하기 위해 계속 같은 코드를 구현하는 것을 피곤하다.
다행히도 Python은 Decorator 기능이 있다.

Decorator기능을 활용해서 간단한 비동기 I/O 함수들은 Thread로 동작하도록 하자.
HTTP Reqeust는 Thread 보다는 async await를 활용한 Coroutine으로 작성하고 안에는 꼭 비동기를 지원하는 패키지를 사용하자.

def using_thread(func: Callable):
    def decorator(*args):
        th = Thread(target=func, args=(*args,))
        th.start()
        return th

    return decorator


@using_thread
def create_pdf(no: int, person: Person):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("helvetica", size=12)
    pdf.cell(txt=f"Name : {person.name}")
    pdf.cell(txt=f"Age : {person.age}")
    pdf.cell(txt=f"Location : {person.location}")
    pdf.output(name=f"data/{uuid.uuid4()}.pdf")
    print(f"{no} is done")


for i, person in enumerate(test_data):
    create_pdf(i, person)

이 기능을 만들때는 ThreadCoroutine 사용에 있어서 주의하자.

엄청 많고 용량이 큰 파일들을 한번에 Download, Upload 등 통신을 할 때는 파일을 전달하기 위한 통신으로 인해 네트워크 리소스를 엄청 잡아먹는다.
따라서, 상황을 먼저 판단해보고 기능의 총 작동 시간은 중요하지 않고 정상적으로 기능의 성공의 여부만 중요하다고 하면 단순 반복문으로 작성하고 Sleep을 조금 주어 주자.

728x90
반응형