python库concurrent 多线程 多进程,快速使用

背景

python多线程threading  用得比较多。最近发现另外一个自带库 concurrent 只用几行代码就可以编写出线程池/进程池。

concurrent.futures 模块提供异步执行可调用对象高层接口。

异步执行可以由

ThreadPoolExecutor 使用线程

或由 ProcessPoolExecutor 使用单独的进程来实现。

两者都是实现抽像类 Executor 定义的接口。

总的来说:

  • 多线程,使用 concurrent.futures.ThreadPoolExecutor 
  • 多进程,使用concurrent.futures.ProcessPoolExecutor 

 

最近在项目中,需要批量造数据,循环1000次或者1万次等太久了。有相关异步多线程的可以参考下面用法

 

 

用法

from concurrent import futures
 
 
 
 
def blocking_way():    #修改这个方法,就可以做成异步了
    url="http://www.baidu.com"
    header= {
               "Content-Type": "application/x-www-form-urlencoded"
            }
    response=requests.get(url+"/registered",headers=header)
    return  response
 
def thread_way(wokers):
    #多线程
    wokers = wokers
    with futures.ThreadPoolExecutor(wokers) as executor:
        futs = {executor.submit(blocking_way) for i in range(wokers)}
    return len([fut.result() for fut in futs])
 
def process_way(wokers):
    #多进程,我在64位win电脑,最大值就是64了。再多会报错
    wokers = wokers
    with futures.ProcessPoolExecutor(wokers) as executor:
        futs = {executor.submit(blocking_way) for i in range(wokers)}
    return len([fut.result() for fut in futs])
 
if __name__ == '__main__':
    n=10    #起多少数量的并发
    number=thread_way(n)    #通过这个发起多线程
    number=process_way(n)  #通过这个发起多进程

 

posted @ 2022-08-01 15:31  快乐开心的大虾  阅读(556)  评论(0)    收藏  举报