How to use 스레팅 의 파이썬?

나는 내 스레딩의 파악하기 위해 파이썬. # 39, ve i& 바라볼 수 있지만, 솔직히, 문서 및 참조용이므로 여러 가지 # 39 m 사에 지나치게 복잡하고 I& mpfs 저들이요 이해.

어떻게 보여줘야 작업을 위한 기술입니까 분할됩니다 멀티-스레딩?

질문에 대한 의견 (6)

이 질문은, 2010년 이후 지금까지 방식으로 실제 단순화 할 수 있느냐는 질문에 "와 함께 간단한 다중스레딩 좁히어 파이썬 [매핑해야] [1] 및 .

아래 코드는 / 블로그 포스트 기사에서 않했노라 하는 말해둘꼐요 체크아웃하려고 (no 소속) - 병렬 처리 기능을 한 줄. 더 좋은 모델 일상적 스레팅 묒뾽 . # 39 - it up, ll 요약하십시오 i& 몇 줄의 아래에 motor1.1end 기술입니까 그냥 코드:

from multiprocessing.dummy import Pool as ThreadPool 
pool = ThreadPool(4) 
results = pool.map(my_function, my_array)

이는 멀티 스레드 버전니다:

results = []
for item in my_array:
    results.append(my_function(item))
  • 설명 *

&gt. 맵 () 은 파이썬 코드를 쉽게 오는 데 있어 가장 중요한 기능 및 준활성 리틀이에요 병렬 처리 기능을 추가할 수 있습니다. 리스프 (lisp 언어, 낯선 사람들을 위한 조치가 매핑해야 충스러웠으니 기능 등 뭔가 특별한 게 있다. 이 기능을 통해 다른 기능을 하는 매핑하므로 시퀀스일.

&gt. 핸들을 통해 우리에게 qic 매핑해야 이터레이션은 e0100042.log 저장하는 기능, 끝 부분에 있는 모든 결과를 핸디 목록.

enter 이미지 여기에 설명을!

  • 구축상의 *

&gt. 병렬 형태로 존재하고, 또한 두 개의 라이브러리가 제공하는 멀티 매핑해야 거의 알려지지 않았으나, 그 같은 환상적인 child:multiprocessing.dummy. 단계:

'는' 무라티프로스싱.두미 동일하게 다중 처리 모듈에서는 [하지만 /dev/raw/raw1 스래드입니다 대신] (https://docs.python.org/2/library/multiprocessing.html # module-multiprocessing.dummy) ( [중요한 차이가] (https://medium.com/@bfortuner/python-multithreading-vs-multiprocessing-73072ce5600b) - 여러 프로세스를 사용하여 cpu 집약형에 묒뾽. 스래드입니다 (동안) 의 IO ):

&gt. 그러나 이 API 는 복제하므로 무라티프로스싱.두미 멀티 스레딩 모듈에서는 주위에서 래퍼 지나지 않는다.

import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 

urls = [
  'http://www.python.org', 
  'http://www.python.org/about/',
  'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
  'http://www.python.org/doc/',
  'http://www.python.org/download/',
  'http://www.python.org/getit/',
  'http://www.python.org/community/',
  'https://wiki.python.org/moin/',
]

# make the Pool of workers
pool = ThreadPool(4) 

# open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)

# close the pool and wait for the work to finish 
pool.close() 
pool.join() 

시기와 결과:

Single thread:   14.4 seconds
       4 Pool:   3.1 seconds
       8 Pool:   1.4 seconds
      13 Pool:   1.3 seconds

전달하기 위해 여러 어레이에는:

results = pool.starmap(function, zip(list_a, list_b))

또는 통과를 상수입니다 및 어레이에서는:

results = pool.starmap(function, zip(itertools.repeat(constant), list_a))

이전 버전의 윈도, 사용하는 경우 여러 인수를 통해 전달할 수 있습니다 (이 해결하십시오] (https://stackoverflow.com/a/5443941/1893275).

(덕분에 user136036 을 도움됐네 주석문입니다.)

[1]: https://docs.python.org/2/library/functions.html # 매핑해야

해설 (30)

39 의 here& 간단한 예: 시도하시려면 필요한 몇 가지 다른 url 과 반품하십시오 첫번째 콘텐트입니다 목격하고서야.

import Queue
import threading
import urllib2

# called by each thread
def get_url(q, url):
    q.put(urllib2.urlopen(url).read())

theurls = ["http://google.com", "http://yahoo.com"]

q = Queue.Queue()

for u in theurls:
    t = threading.Thread(target=get_url, args = (q,u))
    t.daemon = True
    t.start()

s = q.get()
print s

이 경우는 스레팅 간단한 최적화이든 이용되고 있다. 각 서브트레더 uirl 해결하십시오 위해 기다리고 있는 내용을 대기열은 대응해야 한다. 각 스레드는 디먼이 (won& # 39, t 렉시한테서 프로세스 백업하도록 motor1.1end - # 39 에 비해 더 일반적인 경우 주 스레드할 that& 않음). 모든 주요 스레드할 시작될 때까지 기다릴 수 있는 서브트레더스 수행합니까 ',' 큐 '에서' 한 결과 및 종료된 후, 둘 중 하나의 동일팔레트에 (담당하는 down any 서브트레더스 실행해야 할 수 있는 만큼 여전히 they& # 39, re 데몬입니다 스래드입니다).

Python 은 반드시 올바른 사용 스레드를 접속돤 I / O 작업을 (이후 스피통 doesn& # 39, t 사용하는 다중 코어를 실행하십시오 cpu 바인딩되지 묒뾽 어쨌든, 단 하나의 이유는 스레딩용 막고 있지 there& 기다리는 동안, s # 39 이 과정에서 일부 i / o). 가장 좋은 방법은 거의 변함없이 대기열은 농장에서 일을 스래드입니다 아웃해야 work& 그렇고, 이 결과 및 / 또는 수집하십시오 # 39 을 절감할 수 있도록 하고 있으며, 본질적으로 트레이즈라페 they& # 39 에서 걱정, 조건, 이벤트, 세마포어, 기타 인터 스레드할 잠급니다 조정 / 통신 개념.

해설 (14)

&lt b&gt NOTE&lt /b>:;;; 실제 이 &lt (https://docs.python.org/2/library/multiprocessing.html&quot) 에서, a href = &quot, 파이썬, 병렬 처리 콩지름에 &gt multiprocessing&lt /a>;;; 여러 프로세스를 포크하지 모듈에서는 실행되는 평행광 (인해 글로벌 인터프리터 좉툑, 파이썬 스래드입니다 제공하십시오 인터리브를 하지만 실제로 수행되 순차적으로 전용 I / O 작업을 동시에 할 수 있으며, 때 아닌 인터리브를).

그러나 단순히 인터리브를 찾는 경우 (또는 I / O 작업을 수행하는 불구하고 잠급니다 병렬화된 수 있는 글로벌 interpreter), 다음 (http://docs.python.org/library/threading.html&quot),,, a href = &quot &lt &gt threading&lt /a&gt. 모듈은 식사테이블 시작할 수 있습니다. As a really simple acrobatconnectcentral. let& # 39 의 합산 고려해보십시오 큰 문제를 동시에 사용하여 사정거리를 서브랑주 합산:

import threading

class SummingThread(threading.Thread):
     def __init__(self,low,high):
         super(SummingThread, self).__init__()
         self.low=low
         self.high=high
         self.total=0

     def run(self):
         for i in range(self.low,self.high):
             self.total+=i

thread1 = SummingThread(0,500000)
thread2 = SummingThread(500000,1000000)
thread1.start() # This actually causes the thread to run
thread2.start()
thread1.join()  # This waits until the thread has completed
thread2.join()  
# At this point, both threads have completed
result = thread1.total + thread2.total
print result

참고로, 위의 아주 멍청한 acrobatconnectcentral. 전혀 안 않으므로 I / O 와 직렬로 실행됨을 비록 인터리브된 (사용 추가되든지 부담이 컨텍스트로 스위칭이란) 의 영향으로 글로벌 인터프리터 스피통 푸십시오.

해설 (8)

앞서 이 같은 다른 스피통 스래드입니다 I\O 인해 대해서만 사용할 수 있는 길. 다중 코어를 사용할 경우 혜택을 누릴 수 스케쳐내 cpu 바인딩되지 작업을 [다중 처리] (http://docs.python.org/library/multiprocessing.html):

from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()
해설 (5)

그냥 참고, 대기열은 스레딩용 필요하지 않습니다.

이것은 내가 가장 간단한 예를 보여 주는 동시에 실행 중인 프로세스를 짐작할 수 있을 10.

import threading
from random import randint
from time import sleep

def print_number(number):
    # Sleeps a random 1 to 10 seconds
    rand_int_var = randint(1, 10)
    sleep(rand_int_var)
    print "Thread " + str(number) + " slept for " + str(rand_int_var) + " seconds"

thread_list = []

for i in range(1, 10):
    # Instantiates the thread
    # (i) does not make a sequence, so (i,)
    t = threading.Thread(target=print_number, args=(i,))
    # Sticks the thread in a list so that it remains accessible
    thread_list.append(t)

# Starts threads
for thread in thread_list:
    thread.start()

# This blocks the calling thread until the thread whose join() method is called is terminated.
# From http://docs.python.org/2/library/threading.html#thread-objects
for thread in thread_list:
    thread.join()

# Demonstrates that the main process waited for threads to complete
print "Done"
해설 (5)

그러나 이 날 수 있는 답을 알렉스랑 마르텔리 슬라이드에서는 생각해봤죠 는 수정된 버전을 더 유용한 (적어도 나에게).

  • Updated:* 모두에서 python3 는 python2 및
try:
    # for python3
    import queue
    from urllib.request import urlopen
except:
    # for python2 
    import Queue as queue
    from urllib2 import urlopen

import threading

worker_data = ['http://google.com', 'http://yahoo.com', 'http://bing.com']

#load up a queue with your data, this will handle locking
q = queue.Queue()
for url in worker_data:
    q.put(url)

#define a worker function
def worker(url_queue):
    queue_full = True
    while queue_full:
        try:
            #get your data off the queue, and do some work
            url = url_queue.get(False)
            data = urlopen(url).read()
            print(len(data))

        except queue.Empty:
            queue_full = False

#create as many threads as you want
thread_count = 5
for i in range(thread_count):
    t = threading.Thread(target=worker, args = (q,))
    t.start()
해설 (6)

내가 찾은 이 매우 유용합니다. 많은 스래드입니다 만들기 등 여러 가지 작업을 (큰) 코어, 그들로 하여금 실행하십시오. (이 경우, 셸 프로그램을 호출할):

import Queue
import threading
import multiprocessing
import subprocess

q = Queue.Queue()
for i in range(30): #put 30 tasks in the queue
    q.put(i)

def worker():
    while True:
        item = q.get()
        #execute a task: call a shell program and wait until it completes
        subprocess.call("echo "+str(item), shell=True) 
        q.task_done()

cpus=multiprocessing.cpu_count() #detect number of cores
print("Creating %d threads" % cpus)
for i in range(cpus):
     t = threading.Thread(target=worker)
     t.daemon = True
     t.start()

q.join() #block until all tasks are done
해설 (3)

이 때, 다음과 같은 함수 f ',' 스레드할

import threading
threading.Thread(target=f).start()

'F' 를 전달하기 위해 인수만

threading.Thread(target=f, args=(a,b,c)).start()
해설 (5)

[시작 평행광 묒뾽] 의 3 은 파이썬 협업공간을 (https://docs.python.org/dev/library/concurrent.futures.html). 따라서 우리의 작동합니까 간편해집니다.

이 회사는 장치당 [스레드 풀] (https://docs.python.org/dev/library/concurrent.futures.html # 트레더풀렉세쿠터) 및 [프로세스 풀] (https://docs.python.org/dev/library/concurrent.futures.html # 프로세스풀렉세쿠터).

다음 기울기는 insight:

  • 트레더풀렉세쿠터 예 *
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.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()
해설 (0)

예를 들어, 나를 위해 완벽한 스레딩용 모니터링에만 비동기적입니다 이벤트가 있다. 이걸봐 코드입니다.

# thread_test.py
import threading
import time 

class Monitor(threading.Thread):
    def __init__(self, mon):
        threading.Thread.__init__(self)
        self.mon = mon

    def run(self):
        while True:
            if self.mon[0] == 2:
                print "Mon = 2"
                self.mon[0] = 3;

이 코드는 다음과 같은 일을 열어 이피통 세션이고, 함께 즐길 수 있습니다.

>>>from thread_test import Monitor
>>>a = [0]
>>>mon = Monitor(a)
>>>mon.start()
>>>a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2

몇 분 후에

>>>a[0] = 2
Mon = 2
해설 (5)

놀라운 사용하여 새 콘스류t.푸터스 모듈에서는

def sqr(val):
    import time
    time.sleep(0.1)
    return val * val

def process_result(result):
    print(result)

def process_these_asap(tasks):
    import concurrent.futures

    with concurrent.futures.ProcessPoolExecutor() as executor:
        futures = []
        for task in tasks:
            futures.append(executor.submit(sqr, task))

        for future in concurrent.futures.as_completed(futures):
            process_result(future.result())
        # Or instead of all this just do:
        # results = executor.map(sqr, tasks)
        # list(map(process_result, results))

def main():
    tasks = list(range(10))
    print('Processing {} tasks'.format(len(tasks)))
    process_these_asap(tasks)
    print('Done')
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main())

이 모든 이들에게 잘 된 것 같아 집행관 외곽진입 권능은하나님께 사용는 더러운 손을 Java 와 함께 합니다.

또한 사이드 참고: # 39, 란, 우주의 계속 don& 너회의 풀 / t, t forget 닫으십시오 집행 '을 (를)' 컨텍스트로 don& # 39 사용할 경우, 즉 해당 않니다 그러하매 뛰어난 it for you)

해설 (0)

대부분의 사용 설명서 및 자습서는 Python& # 39 의 '' 와 '큐' 모듈에서는 스레팅 그들은 초보자도 압도적인 것으로 비칠 수 있다.

아마도 '의' 모듈에서는 포지셔닝합니다 콘스류t.푸투르스트레더풀렉세쿠터 파이썬 3. 진정한 매력은 조항 및 목록 '을 (를)' 와 함께 수도 있다는 것이다.

from concurrent.futures import ThreadPoolExecutor, as_completed

def get_url(url):
    # Your actual program here. Using threading.Lock() if necessary
    return ""

# List of urls to fetch
urls = ["url1", "url2"]

with ThreadPoolExecutor(max_workers = 5) as executor:

    # Create threads 
    futures = {executor.submit(get_url, url) for url in urls}

    # as_completed() gives you the threads once finished
    for f in as_completed(futures):
        # Get the results 
        rs = f.result()
해설 (0)

내가 본 작품은 수행 중인 이들은 대부분 실제 사례를 여기서 많이 없는 CPU + 바인딩되지. Cpu 의 예를 들어보겠습니다 10 만대, 10.05 만 사이에 있는 모든 작업을 홀수들의 바인딩될 계산합니다. 여기에 4 개의 모든 방법을 사용한

import math
import timeit
import threading
import multiprocessing
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def time_stuff(fn):
    """
    Measure time of execution of a function
    """
    def wrapper(*args, **kwargs):
        t0 = timeit.default_timer()
        fn(*args, **kwargs)
        t1 = timeit.default_timer()
        print("{} seconds".format(t1 - t0))
    return wrapper

def find_primes_in(nmin, nmax):
    """
    Compute a list of prime numbers between the given minimum and maximum arguments
    """
    primes = []

    #Loop from minimum to maximum
    for current in range(nmin, nmax + 1):

        #Take the square root of the current number
        sqrt_n = int(math.sqrt(current))
        found = False

        #Check if the any number from 2 to the square root + 1 divides the current numnber under consideration
        for number in range(2, sqrt_n + 1):

            #If divisible we have found a factor, hence this is not a prime number, lets move to the next one
            if current % number == 0:
                found = True
                break

        #If not divisible, add this number to the list of primes that we have found so far
        if not found:
            primes.append(current)

    #I am merely printing the length of the array containing all the primes but feel free to do what you want
    print(len(primes))

@time_stuff
def sequential_prime_finder(nmin, nmax):
    """
    Use the main process and main thread to compute everything in this case
    """
    find_primes_in(nmin, nmax)

@time_stuff
def threading_prime_finder(nmin, nmax):
    """
    If the minimum is 1000 and the maximum is 2000 and we have 4 workers
    1000 - 1250 to worker 1
    1250 - 1500 to worker 2
    1500 - 1750 to worker 3
    1750 - 2000 to worker 4
    so lets split the min and max values according to the number of workers
    """
    nrange = nmax - nmin
    threads = []
    for i in range(8):
        start = int(nmin + i * nrange/8)
        end = int(nmin + (i + 1) * nrange/8)

        #Start the thrread with the min and max split up to compute
        #Parallel computation will not work here due to GIL since this is a CPU bound task
        t = threading.Thread(target = find_primes_in, args = (start, end))
        threads.append(t)
        t.start()

    #Dont forget to wait for the threads to finish
    for t in threads:
        t.join()

@time_stuff
def processing_prime_finder(nmin, nmax):
    """
    Split the min, max interval similar to the threading method above but use processes this time
    """
    nrange = nmax - nmin
    processes = []
    for i in range(8):
        start = int(nmin + i * nrange/8)
        end = int(nmin + (i + 1) * nrange/8)
        p = multiprocessing.Process(target = find_primes_in, args = (start, end))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

@time_stuff
def thread_executor_prime_finder(nmin, nmax):
    """
    Split the min max interval similar to the threading method but use thread pool executor this time
    This method is slightly faster than using pure threading as the pools manage threads more efficiently
    This method is still slow due to the GIL limitations since we are doing a CPU bound task
    """
    nrange = nmax - nmin
    with ThreadPoolExecutor(max_workers = 8) as e:
        for i in range(8):
            start = int(nmin + i * nrange/8)
            end = int(nmin + (i + 1) * nrange/8)
            e.submit(find_primes_in, start, end)

@time_stuff
def process_executor_prime_finder(nmin, nmax):
    """
    Split the min max interval similar to the threading method but use the process pool executor
    This is the fastest method recorded so far as it manages process efficiently + overcomes GIL limitations
    RECOMMENDED METHOD FOR CPU BOUND TASKS
    """
    nrange = nmax - nmin
    with ProcessPoolExecutor(max_workers = 8) as e:
        for i in range(8):
            start = int(nmin + i * nrange/8)
            end = int(nmin + (i + 1) * nrange/8)
            e.submit(find_primes_in, start, end)

def main():
    nmin = int(1e7)
    nmax = int(1.05e7)
    print("Sequential Prime Finder Starting")
    sequential_prime_finder(nmin, nmax)
    print("Threading Prime Finder Starting")
    threading_prime_finder(nmin, nmax)
    print("Processing Prime Finder Starting")
    processing_prime_finder(nmin, nmax)
    print("Thread Executor Prime Finder Starting")
    thread_executor_prime_finder(nmin, nmax)
    print("Process Executor Finder Starting")
    process_executor_prime_finder(nmin, nmax)

main()

다음은 결과 on my Mac OSX 4 코어 시스템

Sequential Prime Finder Starting
9.708213827005238 seconds
Threading Prime Finder Starting
9.81836523200036 seconds
Processing Prime Finder Starting
3.2467174359990167 seconds
Thread Executor Prime Finder Starting
10.228896902000997 seconds
Process Executor Finder Starting
2.656402041000547 seconds
해설 (4)

가장 간단한 예는 CSV 가져오기의 슬라이드에서는 사용하여 스레팅. [라이브러리란 포함인지 다를 수 있으며 다른 목적을 위한]

도우미 기능:

from threading import Thread
from project import app 
import csv

def import_handler(csv_file_name):
    thr = Thread(target=dump_async_csv_data, args=[csv_file_name])
    thr.start()

def dump_async_csv_data(csv_file_name):
    with app.app_context():
        with open(csv_file_name) as File:
            reader = csv.DictReader(File)
            for row in reader:
                #DB operation/query

드라이버구성 기능:

import_handler(csv_file_name) 
해설 (0)

멀티 스레딩 간단한 예를 들어 어떤 도움이 됩니다. 쉽게 이해하고 어떻게 부여됩니까 멀티 스레드 apc® python 에서 실행할 수 있습니다. 나는 다른 것을 사용한 액세스하려면 때까지 자신의 작품을 위해 이전 스래드입니다 잠급니다 스레드할 하였다. 사용하여

&gt. 트로크 = 스레팅. 부네즈마포어 (가치 = 4)

이 코드 행의 번호를 가질 수 있습니다 한 번에 처리할 수 있는 마친 뒤 이전 또는 이후에 실행하십시오 스레드 미삭 유지할 수 있습니다.

import threading
import time

#tLock = threading.Lock()
tLock = threading.BoundedSemaphore(value=4)
def timer(name, delay, repeat):
    print  "\r\nTimer: ", name, " Started"
    tLock.acquire()
    print "\r\n", name, " has the acquired the lock"
    while repeat > 0:
        time.sleep(delay)
        print "\r\n", name, ": ", str(time.ctime(time.time()))
        repeat -= 1

    print "\r\n", name, " is releaseing the lock"
    tLock.release()
    print "\r\nTimer: ", name, " Completed"

def Main():
    t1 = threading.Thread(target=timer, args=("Timer1", 2, 5))
    t2 = threading.Thread(target=timer, args=("Timer2", 3, 5))
    t3 = threading.Thread(target=timer, args=("Timer3", 4, 5))
    t4 = threading.Thread(target=timer, args=("Timer4", 5, 5))
    t5 = threading.Thread(target=timer, args=("Timer5", 0.1, 5))

    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t5.start()

    print "\r\nMain Complete"

if __name__ == "__main__":
    Main()
해설 (0)

기타 솔루션 실제로 사용된 다중 코어를 on my GNU / 리눅스 서버 (어디서 don& # 39, 관리 권한이 없다). 그들은 그냥 있는 실행했음 단일코어. '낮은 수준' 내가 오스윈포크 인터페이스입니다 여러 프로세스를 실행할 때. 이는 코드와 협력했습니다 가져다줄래요:

from os import fork

values = ['different', 'values', 'for', 'threads']

for i in range(len(values)):
    p = fork()
    if p == 0:
        my_function(values[i])
        break
해설 (0)

간단한 예를 통해 기여하고 싶다 및 설명, 내가 가진 이 문제를 해결할 수 있을 때 유용한 I& # 39 번 찾을 수 있어요.

이 질문에 대한 몇 가지 정보를 찾을 수 있습니다 Python& # 39 의 길 (글로벌 인터프리터 좉툑) 와 매일 사용하는 간단한 예를 몇 가지 간단한 벤치마크 기록되었으므로 무라티프로스싱.두미 구성형.

  • 글로벌 인터프리터 좉툑 (길) *

파이썬 doesn& # 39, t 에 대한 인식이 멀티-스레딩 허용하시겠습니까 진짜 말을해야합니다. 또한 멀티-스레딩 패키지 그러나 스케쳐내 코드 s 에 멀티스레드 가속화하기 위해 it& # 39 위, 다음, 보통 바로 사용할 수 있어 좋습니다. 파이썬 인터프리터 (길) 는 글로벌 잠급니다 chunghwa () 이라고 한다.

39, & # 39 를 통해 확인할 수 있는 길 하나만 threads&. 한 번에 실행할 수 있다.

스레드 통과할 길 (gil, 수행합니까 리틀이에요 작동합니까 관심용 가져옵니다 관용으로충만하신 다음 어떨까. 이런 인간의 눈은 매우 빠르게 스래드입니다 병렬로 수행할 수 있도록 좋아하는 것처럼 보일 수도 있습니다 하지만 이들은 정말 한 번씩 같은 CPU 코어. 이 모든 길 반군지역 오버헤드에 자도으로 실행에. 즉, 다음 코드에서 사용하는 보다 빠르게 실행할 수 있도록 스케쳐내 스레팅

39 는 종종 isn& 패키지, 좋은 아이디어입니다.

39 의 스레팅 패키지로의 Python& 사용하는 데는 있습니다.

동시에 실행할 경우, 효율성, 몇 가지 문제가 없습니다 그럼 it& 완전히 fine & # 39 의 편리하잖아요 또는 기다려야 하는 코드를 실행할 경우 어떤 것 (like some 입출력 (i / o)) 을 많이 만들 수 있다고 한다. 그러나 스레팅 라이브러리란 won& # 39, t 사용하면 추가 CPU 코어.

운영 체제 (수행여 멀티-프로세싱), 아웃소싱 체제로 멀티-스레딩 수 있습니다. 네 파이썬 코드를 호출하는 일부 외부 응용 프로그램 (예, 스파크 (spark) 또는 Hadoop), 또는 일부 사용 중인 파이썬 코드를 코드에서는 (예: 외상때문에 너회의 파이썬 코드를 C 함수를 호출할 수 있는 높여줍니까 비싸다구요 멀티스레디드 stuff).

    • 중요한 이유

때문에 많은 사람들은 그들의 돌림무늬 병목 현상을 찾는 시간을 들여서 파이썬 코드를 어떻게 알게 전에 멀티스레디드 길 입니다.

일단 이 정보는 here& 선택해제합니다 # 39 의 내 코드:

#!/bin/python
from multiprocessing.dummy import Pool
from subprocess import PIPE,Popen
import time
import os

# In the variable pool_size we define the "parallelness".
# For CPU-bound tasks, it doesn't make sense to create more Pool processes
# than you have cores to run them on.
#
# On the other hand, if you are using I/O-bound tasks, it may make sense
# to create a quite a few more Pool processes than cores, since the processes
# will probably spend most their time blocked (waiting for I/O to complete).
pool_size = 8

def do_ping(ip):
    if os.name == 'nt':
        print ("Using Windows Ping to " + ip)
        proc = Popen(['ping', ip], stdout=PIPE)
        return proc.communicate()[0]
    else:
        print ("Using Linux / Unix Ping to " + ip)
        proc = Popen(['ping', ip, '-c', '4'], stdout=PIPE)
        return proc.communicate()[0]

os.system('cls' if os.name=='nt' else 'clear')
print ("Running using threads\n")
start_time = time.time()
pool = Pool(pool_size)
website_names = ["www.google.com","www.facebook.com","www.pinterest.com","www.microsoft.com"]
result = {}
for website_name in website_names:
    result[website_name] = pool.apply_async(do_ping, args=(website_name,))
pool.close()
pool.join()
print ("\n--- Execution took {} seconds ---".format((time.time() - start_time)))

# Now we do the same without threading, just to compare time
print ("\nRunning NOT using threads\n")
start_time = time.time()
for website_name in website_names:
    do_ping(website_name)
print ("\n--- Execution took {} seconds ---".format((time.time() - start_time)))

# Here's one way to print the final output from the threads
output = {}
for key, value in result.items():
    output[key] = value.get()
print ("\nOutput aggregated in a Dictionary:")
print (output)
print ("\n")

print ("\nPretty printed output:")
for key, value in output.items():
    print (key + "\n")
    print (value)
해설 (0)

우리가 알고 있는 이 게시물로의 에서 빌린 다중스레딩, 다중 처리 및 비동기 및 그 사이의 선택에 대한 사용.

  • Python3* 에는 새로운 내장현 위해 라이브러리를 동시성 및 병렬 처리: 콘스류t.푸터스

그래서 제시하십시오 실행하기 위한 실험을 통해 4 개의 작업 (즉 '이슬레예프 ()' 방법) '에서' 스레팅 풀 분할합니다:

from concurrent.futures import ThreadPoolExecutor, as_completed
from time import sleep, time

def concurrent(max_worker=1):
    futures = []

    tick = time()
    with ThreadPoolExecutor(max_workers=max_worker) as executor:
        futures.append(executor.submit(sleep, 2))
        futures.append(executor.submit(sleep, 1))
        futures.append(executor.submit(sleep, 7))
        futures.append(executor.submit(sleep, 3))

        for future in as_completed(futures):
            if future.result() is not None:
                print(future.result())

    print('Total elapsed time by {} workers:'.format(max_worker), time()-tick)

concurrent(5)
concurrent(4)
concurrent(3)
concurrent(2)
concurrent(1)

아웃해야:

Total elapsed time by 5 workers: 7.007831811904907
Total elapsed time by 4 workers: 7.007944107055664
Total elapsed time by 3 workers: 7.003149509429932
Total elapsed time by 2 workers: 8.004627466201782
Total elapsed time by 1 workers: 13.013478994369507
  • [ 참고 ):

  • 위의 가장 좋은 결과를 볼 수 있듯이, 그 사건은 '3' 근로자들은요 4 개 과제.

  • I / O 작업을 처리할 경우 대신 바인딩되지 (스레드할 사용하여 '') '을 (를)' '' 트레더풀렉세쿠터 프로세스풀렉세쿠터 변경할 수 있습니다

해설 (0)
import threading
import requests

def send():

  r = requests.get('https://www.stackoverlow.com')

thread = []
t = threading.Thread(target=send())
thread.append(t)
t.start()
해설 (5)