ThreadPoolExecutorのスレッドプールとProcessPoolExecutorプロセスプール

ProcessPoolExecutorスレッドプール

あなたは20個のスレッドを作成した場合のみ、3つのスレッドを実行している可能にしながら1.なぜ我々は、スレッドプールにそれが必要なのですが、20個のスレッドが作成および破棄、スレッドを作成する必要があり、システムリソースを消費する必要があるので、スレッドプールのアイデアこれは次のとおりです。各スレッドは、それぞれのタスク、残りのタスクがキューイングされている皮膚を割り当てられ、スレッドがタスクを完了すると、タスクキューは、このスレッドを継続するために手配することができます

2、concurrent.futures ProcessPoolExecutorとThreadPoolExecutor二つのクラス、スレッドの実現とマルチプロセッシングさらに抽象(メインここで懸念スレッド・プール)を提供し、標準ライブラリモジュールを、あなたが行うことができ、自動的にスレッドをディスパッチするために私たちを助けることができないだけで。

<ul>
    <li>主线程可以获取某一个线程(或者任务)的状态,以及返回值</li>
    <li>当一个线程完成的时候,主线程能够立即知道</li>
    <li>让多线程和多进程的编码接口一致</li>
</ul>

使用するのは簡単

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import time
#参数times用来模拟网络请求时间
def get_html(times):
    print("get page {}s finished".format(times))
    return times
executor = ThreadPoolExecutor(max_workers=2)
#通过submit函数提交执行的函数到线程池中,submit函数立即返回,不阻塞
task1 = executor.submit(get_html,(3))
task2 = executor.submit(get_html,(2))
#done方法用于判断某个任务是否完成
print(task1.done())
#cancel方法用于取消某个任务,该任务没有放到线程池中才能被取消
print(task2.cancel())
print(task1.done())
#result方法可以获取task的执行结果
print(task1.result())

#结果:
# get page 3s finished
# get page 2s finished
# True
# False
# True
# 3
  • ThreadPoolExecutor施工時間インスタンス、渡しmax_workersの同じ時刻に実行するスレッドでスレッド数を設定するパラメータを
  • 使用提出スレッドを提出する機能をスレッドプールにタスク(関数名やパラメータ)を実行する必要がある、と注意し、(ファイルと同様に、描画)そのタスクを扱う返す(提出)の代わりにブロックするが、すぐに戻りました。
  • 提出する関数によって返さタスク・ハンドル、使用ができます()に行わ完了したタスクを決定する方法を
  • 使用結果()メソッドは、内部コードを表示する、私は、このメソッドがブロックされて見つかった、タスクの戻り値を取得します

as_completed

上記ミッションの終わりには、常にメインスレッドで判断しないかどうかを判断するための方法を提供していますが、時には我々は仕事が終わって聞いて、結果を得るために行ってきましたが、常にそこに終わらない、各タスクを判断しません。これは、すべてのタスクの結果からas_completed使用することができる方法です。

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor,as_completed
import time
#参数times用来模拟网络请求时间
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times
executor = ThreadPoolExecutor(max_workers=2)
urls = [3,2,4]
all_task = [executor.submit(get_html,(url)) for url in urls]
for future in as_completed(all_task):
    data = future.result()
    print("in main:get page {}s success".format(data))

#结果
# get page 2s finished
# in main:get page 2s success
# get page 3s finished
# in main:get page 3s success
# get page 4s finished
# in main:get page 4s success

地図

上記as_completed方法に加え方法もをexecumap使用することができるが、少し異なる、送信方法を用いて、予めことなく、マップ法をマップ法を使用してPythonの標準ライブラリの意味をマッピング同じであり、各要素のシーケンスであります同じ機能を実行します。上記のコードでは、各要素のURLのすべての実行get_html関数であり、各スレッドプールを割り当てます。あなたはタスクが最初2Sを終了した場合であっても、異なる結果がas_completed上記の実行結果の方法、同じ出力系列順とURLのリストを見ることができ、3Sは、印刷ジョブが2Sを完了する前に完了したタスクをプリントアウトします

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor,as_completed
import time
#参数times用来模拟网络请求时间
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times
executor = ThreadPoolExecutor(max_workers=2)
urls = [3,2,4]
for data in executor.map(get_html,urls):
    print("in main:get page {}s success".format(data))

#结果
# get page 2s finished
# get page 3s finished
# in main:get page 3s success
# in main:get page 2s success
# get page 4s finished
# in main:get page 4s success

待つ

waitメソッドは、設定された要件を満たすまで、メインスレッドをブロックすることができます。タスクシーケンス待ち法待ってタイムアウト条件、待って、3つのパラメータを受け入れます。条件return_whenデフォルトALL_COMPLETEDを待って、あなたが夜を過ごすためにすべてのタスクを待ちたいことを示しています。あなたは、メインスレッドがちょうどプリントアウトし、それは確かにすべてのタスクが完了している、メイン、FIRST_COMPLETEDに設定できる条件を待っている、それは最初のタスクを停止して待機するように完成さを表す結果を見ることができます

# -*-coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED,FIRST_COMPLETED
import time
#参数times用来模拟网络请求时间
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times
executor = ThreadPoolExecutor(max_workers=2)
urls = [3,2,4]
all_task = [executor.submit(get_html,(url)) for url in urls]
wait(all_task,return_when=ALL_COMPLETED)
print("main")
#结果
# get page 2s finished
# get page 3s finished
# get page 4s finished
# main

ProcessPoolExecutor

途中、同期呼び出し方法:ジョブリターン結果を得るには、まだタスク実行の終了を待って、タスクを送信。そして、次のコード行は、シリアル実行タスクになります

# -*- coding:utf-8 -*-
# 方式一、同步调用方式:提交任务,原地等待任务执行结束,拿到任务返回结果。再执行下一行代码会导致任务串行执行

# 进程池的两种任务提交方式

import datetime
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import current_thread
import time, random, os
import requests
def task(name):
    print('%s %s is running'%(name,os.getpid()))
    #print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
if __name__ == '__main__':
    p=ProcessPoolExecutor(4) #设置进程池内进程数
    for i in range(10):
        #同步调用方式,调用和等值
        obj = p.submit(task,"进程pid:")#传参方式(任务名,参数),参数使用位置或者关键字参数
        res =obj.result()
    p.shutdown(wait=True) #关闭进程池的入口,等待池内任务运行结束
    print("主")

非同期提出

def task(name):
    print("%s %s is running" %(name,os.getpid()))
    time.sleep(random.randint(1,3))

if __name__ == '__main__':
    p = ProcessPoolExecutor(4) #设置进程池内进程
    for i in range(10):
        #异步调用方式,只调用,不等值
        p.submit(task,'进程pid:') #传参方式(任务名,参数),参数使用位置参数或者关键字参数
    p.shutdown(wait=True)
    print('主')

同期プロセスの起動プール

同期呼び出しの長所、短所をデカップリング:遅いです

def get(url):
    print('%s GET %s' % (os.getpid(),url))
    time.sleep(3)
    response = requests.get(url)
    if response.status_code == 200:
        res = response.text
    else:
        res = "下载失败"
    return res

def parse(res):
    time.sleep(1)
    print("%s 解析结果为%s" %(os.getpid(),len(res)))

if __name__ == "__main__":
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',

    ]
    p=ProcessPoolExecutor(9)
    l=[]
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
        l.append(future)
    p.shutdown(wait=True)

    for future in l:
        parse(future.result())
    print('完成时间:',time.time()-start)
    #完成时间: 13.209137678146362

非同期呼び出し

非同期呼び出し:カップリングの欠点、速いスピードの利点

def get(url):
    print('%s GET %s' % (os.getpid(),url))
    time.sleep(3)
    reponse = requests.get(url)
    if reponse.status_code == 200:
        res = reponse.text
    else:
        res = "下载失败"
    parse(res)

def parse(res):
    time.sleep(1)
    print('%s 解析结果为%s' %(os.getpid(),len(res)))

if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',

    ]

    p = ProcessPoolExecutor(9)
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
    p.shutdown(wait=True)
    print("完成时间",time.time()-start)#完成时间 6.293345212936401

2-1-4プロセスプール、非同期呼び出し+コールバック関数:カップリングを解く、遅い(+非同期呼び出しのコールバック)

def get(url):
    print('%s GET %s' % (os.getpid(), url))
    time.sleep(3)
    response = requests.get(url)
    if response.status_code == 200:
        res = response.text
    else:
        res = '下载失败'
    return res

def parse(future):
    time.sleep(1)
    # 传入的是个对象,获取返回值 需要进行result操作
    res = future.result()
    print("res",)
    print('%s 解析结果为%s' % (os.getpid(), len(res)))



if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',
    ]
    p = ProcessPoolExecutor(9)
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
        #模块内的回调函数方法,parse会使用future对象的返回值,对象返回值是执行任务的返回值
        #回调应该是相当于parse(future)
        future.add_done_callback(parse)

    p.shutdown(wait=True)
    print("完成时间",time.time()-start)#完成时间 33.79998469352722

スレッドプール:+非同期コールバック---- IO集約型の主要な使用、スレッドプール:実行する操作を行った利用者のために

def get(url):
    print("%s GET %s" %(current_thread().name,url))
    time.sleep(3)
    reponse = requests.get(url)
    if reponse.status_code == 200:
        res = reponse.text
    else:
        res = "下载失败"
    return res

def parse(future):
    time.sleep(1)
    res = future.result()
    print("%s 解析结果为%s" %(current_thread().name,len(res)))

if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',
    ]
    p = ThreadPoolExecutor(4)
    start = time.time()
    for url in urls:
        future = p.submit(get,url)
        future.add_done_callback(parse)
    p.shutdown(wait=True)
    print("主",current_thread().name)
    print("完成时间",time.time()-start)#完成时间 32.52604126930237

1は、スレッドは、コンテキストスイッチが(記録管理に置く)のCPUを必要とすることはできません。

オープン手順が実行されるプロセスは、さ:2、プロセスは、スレッドよりもリソースを消費する工場と同等のものを処理し、工場が共通の資源の恩恵を受けて内部の人々は、多くの人々がある,,プロセスでは、デフォルトは、次のような唯一のメインスレッドは、ここでスレッドは、スレッドが動作するように、同時に複数の人を作成するだけのプロセスです。

3、スレッドは、GILグローバルロック解除があります:CPUスケジューリングを許可していません。

4、計算された密度は、マルチプロセスに適しています

図5に示すように、スレッド:スレッドで作動するコンピュータの最小単位であります

6、工程:デフォルトのメインスレッドのマルチスレッドを共存させることができます(仕事を助けるために)

7、コルーチン:スレッド、複数のタスクを実行するためのプロセス、複数のタスクを実行するプロセスを一つのスレッドを使用して、マイクロスレッド

8、GILグローバルインタプリタロックは1つだけのスレッドがCPUを予定されていることを保証するために、

投稿者:https://www.jianshu.com/p/b9b3d66aa0be

投稿者:https://blog.csdn.net/qq_33961117/article/details/82587873

おすすめ

転載: www.cnblogs.com/venvive/p/11601190.html