Development Tip

스레드 대 스레딩

yourdevel 2020. 12. 11. 20:21
반응형

스레드 대 스레딩


Python에서 모듈 threadingthread모듈 의 차이점은 무엇입니까 ?


Python 3에서는 thread이름이 _thread. 를 구현하는 데 사용되는 인프라 코드 threading이며 일반적인 Python 코드가 그 근처에 있으면 안됩니다.

_thread기본 OS 수준 프로세스에 대한 상당히 원시적 인보기를 제공합니다. 이것은 거의 원하는 것이 아니므로 Py3k에서 이름을 변경하여 실제로 구현 세부 사항임을 나타냅니다.

threading 몇 가지 추가 자동 회계 및 여러 편의 유틸리티를 추가하여 표준 Python 코드에 선호되는 옵션입니다.


threading인터페이스하는 더 높은 수준의 모듈입니다 thread.

threading문서 는 여기를 참조하십시오 .

http://docs.python.org/library/threading.html


제가 잘못 본게 아니라면, thread당신이 실행할 수있는 기능을 가진 반면, 별도의 스레드로 threading당신이 해야 만들 클래스를 하지만, 더 많은 기능을 얻을.

편집 : 이것은 정확하지 않습니다. threading모듈은 스레드를 만드는 다양한 방법을 제공합니다.

  • threading.Thread(target=function_name).start()
  • threading.Thread자신의 run()메서드로 의 자식 클래스를 만들고 시작합니다.

스레딩에 사용할 수 있고 완벽하게 작동하는 Python 라이브러리가 하나 더 있습니다.

concurrent.futures 라는 라이브러리 . 이것은 우리의 일을 더 쉽게 만듭니다.

그것은을 위해이 스레드 풀링프로세스 풀링 .

다음은 통찰력을 제공합니다.

ThreadPoolExecutor 예제

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

또 다른 예

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ThreadPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

The module "Thread" treats a thread as a function, while the module "threading" is implemented in an object oriented way, i.e. every thread corresponds to an object.

참고URL : https://stackoverflow.com/questions/5568555/thread-vs-threading

반응형