[Python] Concurrency Thread Decorator - 3

2022. 8. 14. 00:12·Python/Python
반응형

[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)

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

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

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)
'Python/Python' 카테고리의 다른 글
  • [Python] lru_cache
  • [Python] Object class __slots__를 이용한 성능 개선
  • [Python] Concurrency PDF 파일 생성 - 2
  • [Python] Concurrency 어떤 경우에 어떤 것을 사용하는게 좋을까 - 1
상쾌한기분
상쾌한기분
  • 상쾌한기분
    상쾌한기분
    상쾌한기분
  • 전체
    오늘
    어제
    • 분류 전체보기 (250)
      • Python (44)
        • Python (26)
        • Django (6)
        • Flask (4)
        • Open Source (6)
      • Kotlin & Java (5)
        • Spring (2)
        • 프로젝트 (1)
      • Go (11)
      • Database (24)
        • MySQL (21)
        • Redis (3)
      • Infrastructure (2)
        • CDC (4)
        • Kafka (5)
        • Prometheus (2)
        • Fluentd (11)
        • Docker (1)
        • Airflow (2)
        • VPN (2)
      • IT (25)
        • AI (9)
        • Langchain (8)
        • Web (18)
        • Git (8)
        • 리팩토링 (9)
        • Micro Service Architecture (8)
        • Clean Code (16)
        • Design Pattern (0)
        • 수학 (1)
        • 알고리즘 (14)
      • OS (14)
        • Centos (10)
        • Ubuntu (3)
        • Mac (1)
      • Search Engine (2)
        • ElasticSearch (1)
        • Lucene Solr (1)
      • PHP (2)
        • Laravel (1)
        • Codeigniter (1)
  • 블로그 메뉴

    • Github 방문
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    ollama
    LLM
    CDC
    Langchain
    fluentd
    prompt
    MYSQL
    http
    티스토리챌린지
    오블완
    performance
    docker
    백준
    Redis
    파이썬
    Golang
    go
    git
    python
    Kafka
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
상쾌한기분
[Python] Concurrency Thread Decorator - 3
상단으로

티스토리툴바