> 백엔드 개발 > 파이썬 튜토리얼 > 멀티 스레딩 및 멀티 프로세싱을위한 우수한 파이썬 기술 : 앱 성능 향상

멀티 스레딩 및 멀티 프로세싱을위한 우수한 파이썬 기술 : 앱 성능 향상

Linda Hamilton
풀어 주다: 2025-01-27 18:12:14
원래의
418명이 탐색했습니다.

owerful Python Techniques for Multithreading and Multiprocessing: Boost Your App Performance

내 Amazon 작가 페이지에서 다양한 책을 찾아보세요. 더 많은 통찰력과 업데이트를 보려면 Medium에서 저를 팔로우하세요! 여러분의 많은 지원 부탁드립니다.

Python의 멀티스레딩 및 멀티프로세싱 기능을 활용하여 애플리케이션의 속도와 효율성을 획기적으로 향상시키세요. 이 가이드에서는 이러한 기능을 효과적으로 활용하기 위한 8가지 필수 기술을 소개합니다.

스레딩은 I/O 중심 작업에 탁월합니다. Python의 threading 모듈은 스레드 관리를 위한 사용자 친화적인 인터페이스를 제공합니다. 여러 파일을 동시에 다운로드하는 방법은 다음과 같습니다.

<code class="language-python">import threading
import requests

def download_file(url):
    response = requests.get(url)
    filename = url.split('/')[-1]
    with open(filename, 'wb') as f:
        f.write(response.content)
    print(f"Downloaded {filename}")

urls = ['http://example.com/file1.txt', 'http://example.com/file2.txt', 'http://example.com/file3.txt']

threads = []
for url in urls:
    thread = threading.Thread(target=download_file, args=(url,))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

print("All downloads complete")</code>
로그인 후 복사

이 코드는 각 다운로드를 별도의 스레드에 할당하여 동시 실행을 가능하게 합니다.

CPU 바인딩 작업의 경우 Python의 GIL(Global Interpreter Lock) 덕분에 multiprocessing 모듈이 더 우수합니다. 멀티프로세싱은 각각 고유한 메모리 공간과 GIL을 갖춘 독립적인 프로세스를 생성하여 GIL의 제한을 피합니다. 다음은 병렬 계산의 예입니다.

<code class="language-python">import multiprocessing

def calculate_square(number):
    return number * number

if __name__ == '__main__':
    numbers = range(10)

    with multiprocessing.Pool() as pool:
        results = pool.map(calculate_square, numbers)

    print(results)</code>
로그인 후 복사

프로세스 풀을 활용하여 계산을 효율적으로 분배합니다.

concurrent.futures 모듈은 스레드와 프로세스 모두에서 원활하게 작동하는 비동기 작업 실행을 위한 더 높은 수준의 추상화를 제공합니다. 다음은 ThreadPoolExecutor:

를 사용한 예입니다.
<code class="language-python">from concurrent.futures import ThreadPoolExecutor
import time

def worker(n):
    print(f"Worker {n} starting")
    time.sleep(2)
    print(f"Worker {n} finished")

with ThreadPoolExecutor(max_workers=3) as executor:
    executor.map(worker, range(5))

print("All workers complete")</code>
로그인 후 복사

5개의 작업자 작업을 관리하는 스레드 풀이 생성됩니다.

비동기 I/O의 경우 asyncio 모듈이 빛을 발하여 코루틴을 사용한 효율적인 비동기 프로그래밍을 가능하게 합니다. 예는 다음과 같습니다.

<code class="language-python">import asyncio
import aiohttp

async def fetch_url(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    urls = ['http://example.com', 'http://example.org', 'http://example.net']
    tasks = [fetch_url(url) for url in urls]
    results = await asyncio.gather(*tasks)
    for url, result in zip(urls, results):
        print(f"Content length of {url}: {len(result)}")

asyncio.run(main())</code>
로그인 후 복사

이렇게 하면 여러 URL에서 동시에 콘텐츠를 효율적으로 가져올 수 있습니다.

프로세스 간 데이터 공유에는 특정 도구가 필요합니다. multiprocessing 모듈은 공유 메모리를 위한 Value과 같은 메커니즘을 제공합니다.

<code class="language-python">from multiprocessing import Process, Value
import time

def increment(counter):
    for _ in range(100):
        with counter.get_lock():
            counter.value += 1
        time.sleep(0.01)

if __name__ == '__main__':
    counter = Value('i', 0)
    processes = [Process(target=increment, args=(counter,)) for _ in range(4)]

    for p in processes:
        p.start()

    for p in processes:
        p.join()

    print(f"Final counter value: {counter.value}")</code>
로그인 후 복사

이는 여러 프로세스에 걸친 안전한 카운터 증가를 보여줍니다.

스레드 동기화는 여러 스레드가 공유 리소스에 액세스할 때 경쟁 조건을 방지합니다. Python은 Lock:

과 같은 동기화 프리미티브를 제공합니다.
<code class="language-python">import threading

class Counter:
    def __init__(self):
        self.count = 0
        self.lock = threading.Lock()

    def increment(self):
        with self.lock:
            self.count += 1

def worker(counter, num_increments):
    for _ in range(num_increments):
        counter.increment()

counter = Counter()
threads = []
for _ in range(5):
    thread = threading.Thread(target=worker, args=(counter, 100000))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

print(f"Final count: {counter.count}")</code>
로그인 후 복사

이 예에서는 원자 카운터 증가를 보장하기 위해 잠금을 사용합니다.

ProcessPoolExecutor은 CPU 바인딩 작업에 이상적입니다. 다음은 소수를 찾는 예입니다.

<code class="language-python">from concurrent.futures import ProcessPoolExecutor
import math

def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

if __name__ == '__main__':
    numbers = range(100000)
    with ProcessPoolExecutor() as executor:
        results = list(executor.map(is_prime, numbers))
    print(sum(results))</code>
로그인 후 복사

이렇게 하면 여러 프로세스에 걸쳐 소수 검사가 분산됩니다.

멀티스레딩과 멀티프로세싱 중에서 선택하는 것은 작업에 따라 다릅니다. I/O 바인딩 작업은 멀티스레딩의 이점을 누리는 반면, CPU 바인딩 작업에는 진정한 병렬 처리를 위해 다중 처리가 필요한 경우가 많습니다. 로드 밸런싱과 작업 종속성은 병렬 처리에서 중요한 고려 사항입니다. 공유 리소스를 처리할 때는 적절한 동기화 메커니즘이 필수적입니다. 성능 비교는 작업 및 시스템에 따라 다릅니다. 데이터 처리 및 과학 컴퓨팅에서는 다중 처리가 매우 효과적일 수 있습니다. 웹 애플리케이션의 경우 asyncio은 동시 연결을 효율적으로 처리합니다. Python의 다양한 병렬 처리 도구를 사용하면 개발자가 고성능 애플리케이션을 만들 수 있습니다.


101권

작가

Aarav Joshi가 공동 설립한 AI 기반 출판사인 101 Books는 저렴한 고품질 도서를 제공하며 일부 도서는 $4.

아마존에서

Golang Clean Code 책을 찾아보세요. Aarav Joshi를 검색해 더 많은 책과 특별 할인을 만나보세요!

기타 프로젝트

다른 프로젝트 살펴보기:

Investor Central(영어, 스페인어, 독일어), Smart Living, Epochs & Echoes, Puzzling Mysteries, 힌두트바, 엘리트 Dev, JS Schools


Medium에서 팔로우하세요

Medium에서 우리와 소통하세요:

Tech Koala Insights, Epochs & Echoes World, Investor Central Medium, Puzzling Mysteries Medium, 과학 및 신기원 매체현대 힌두트바.

위 내용은 멀티 스레딩 및 멀티 프로세싱을위한 우수한 파이썬 기술 : 앱 성능 향상의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿