Python开发【模块】:Concurrent
concurrent 模块
回顾:
对于python来说,作为解释型语言,Python的解释器必须做到既安全又高效。我们都知道多线程编程会遇到的问题,解释器要留意的是避免在不同的线程操作内部共享的数据,同时它还要保证在管理用户线程时保证总是有最大化的计算资源。而python是通过使用全局解释器锁来保护数据的安全性:
多线程执行方式:
- 设置GIL(global interpreter lock).
- 切换到一个线程执行。
- 运行:
- a,指定数量的字节码指令。
- b,线程主动让出控制(可以调用time.sleep(0))。
- 把线程设置为睡眠状态。
- 解锁GIL.
- 再次重复以上步骤。
threading使用回顾:
import threading
import time def run(n):
semaphore.acquire()
time.sleep(2)
print("run the thread: %s" % n)
semaphore.release() if __name__ == '__main__':
start_time = time.time()
thread_list = []
semaphore = threading.BoundedSemaphore(5) # 信号量,最多允许5个线程同时运行
for i in range(20):
t = threading.Thread(target=run, args=(i,))
t.start()
thread_list.append(t)
for t in thread_list:
t.join() used_time = time.time() - start_time
print('用时',used_time) # 用时 8.04102110862732
ThreadPoolExecutor多并发:
1、submit
import time
from concurrent import futures def run(n):
time.sleep(2)
print("run the thread: %s" % n) if __name__ == '__main__':
start = time.time()
with futures.ThreadPoolExecutor(5) as executor:
for i in range(20):
executor.submit(run,i) print(time.time()-start) # 8.006775379180908
2、map
import time
from concurrent import futures def run(n):
time.sleep(2)
print("run the thread: %s" % n) if __name__ == '__main__':
start = time.time()
with futures.ThreadPoolExecutor(5) as executor:
executor.map(run,range(20)) print(time.time()-start) # 8.006775379180908
executor.submit 和 futures.as_completed 这个组合比executor.map 更灵活,因为 submit 方法能处理不同的可调用对象和参数,而 executor.map 只能处理参数不同的同一个可调用对象。此外,传给 futures.as_completed 函数的期物集合可以来自多个 Executor 实例,例如一些由 ThreadPoolExecutor 实例创建,另一些由ProcessPoolExecutor创建
ProcessPoolExecutor多并发:
1、submit
import time
from concurrent import futures import time
from concurrent import futures def run(n):
time.sleep(2)
print("run the thread: %s" % n) if __name__ == '__main__':
start = time.time()
with futures.ProcessPoolExecutor(5) as executor:
for i in range(20):
executor.submit(run, i) print(time.time() - start) # 8.365714311599731
2、map
import time
from concurrent import futures import time
from concurrent import futures def run(n):
time.sleep(2)
print("run the thread: %s" % n) if __name__ == '__main__':
start = time.time()
with futures.ProcessPoolExecutor(5) as executor:
executor.map(run, range(20)) print(time.time() - start) # 8.317736864089966
接口压力测试的脚本
# #!/usr/bin/env python
# # -*- coding:utf-8 -*- import os
import time
import logging
import requests
import threading
from multiprocessing import Lock,Manager
from concurrent import futures download_url = 'http://192.168.188.105:8888'
workers = 250
cpu_count = 4 session = requests.Session() def handle(cost,mutex,contain):
with mutex:
min_cost = contain['min_cost']
max_cost = contain['max_cost']
hit_count = contain['hit_count']
average_cost = contain['average_cost']
if min_cost == 0:
contain['min_cost'] = cost
if min_cost > cost:
contain['min_cost'] = cost
if max_cost < cost:
contain['max_cost'] = cost
average_cost = (average_cost*hit_count + cost) / (hit_count + 1)
hit_count +=1
contain['average_cost'] = average_cost
contain['hit_count'] = hit_count
logging.info(contain) def download_one(mutex,contain):
while True:
try:
stime = time.time()
request = requests.Request(method='GET', url=download_url,)
prep = session.prepare_request(request)
response = session.send(prep, timeout=50)
etime = time.time()
print(response.status_code)
logging.info('process[%s] thread[%s] status[%s] cost[%s]',os.getpid(),threading.current_thread().ident,
response.status_code,etime-stime)
handle(float(etime-stime),mutex,contain)
# time.sleep(1)
except Exception as e:
logging.error(e)
print(e) def new_thread_pool(mutex,contain):
with futures.ThreadPoolExecutor(workers) as executor:
for i in range(workers):
executor.submit(download_one,mutex,contain) def subprocess():
manager = Manager()
mutex = manager.Lock()
contain = manager.dict({'average_cost': 0, 'min_cost': 0, 'max_cost': 0, 'hit_count': 0}) with futures.ProcessPoolExecutor(cpu_count) as executor:
for i in range(cpu_count):
executor.submit(new_thread_pool,mutex,contain) if __name__ == '__main__':
logging.basicConfig(filename="client.log", level=logging.INFO,
format="%(asctime)s [%(filename)s:%(lineno)d] %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]")
subprocess()
Python开发【模块】:Concurrent的更多相关文章
- python 全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)
昨日内容回顾 线程什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的 一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的在当 ...
- python全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)
昨日内容回顾 线程 什么是线程? 线程是cpu调度的最小单位 进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的 ...
- Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures
参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...
- Python标准模块--concurrent.futures(进程池,线程池)
python为我们提供的标准模块concurrent.futures里面有ThreadPoolExecutor(线程池)和ProcessPoolExecutor(进程池)两个模块. 在这个模块里他们俩 ...
- Python标准模块--concurrent.futures
1 模块简介 concurrent.futures模块是在Python3.2中添加的.根据Python的官方文档,concurrent.futures模块提供给开发者一个执行异步调用的高级接口.con ...
- Python标准模块--concurrent.futures 进程池线程池终极用法
concurrent.futures 这个模块是异步调用的机制concurrent.futures 提交任务都是用submitfor + submit 多个任务的提交shutdown 是等效于Pool ...
- python开发模块基础:re正则
一,re模块的用法 #findall #直接返回一个列表 #正常的正则表达式 #但是只会把分组里的显示出来#search #返回一个对象 .group()#match #返回一个对象 .group() ...
- python开发模块基础:异常处理&hashlib&logging&configparser
一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...
- python开发模块基础:os&sys
一,os模块 os模块是与操作系统交互的一个接口 #!/usr/bin/env python #_*_coding:utf-8_*_ ''' os.walk() 显示目录下所有文件和子目录以元祖的形式 ...
- python开发模块基础:序列化模块json,pickle,shelve
一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...
随机推荐
- xshell-常用指令汇总 linux 常用指令
suse linux 常用命令 (1)命令ls——列出文件 ls -la 给出当前目录下所有文件的一个长列表,包括以句点开头的“隐藏”文件 ls a* 列出当前目录下以字母a开头的所有文件 l ...
- NET Core 环境搭建和命令行CLI入门[转]
NET Core 环境搭建和命令行CLI入门 时间:2016-07-06 01:48:19 阅读:258 评论:0 收藏:0 [点我收藏+] 标签: N ...
- Python使用paramiko库远程安全连接SSH
#!/usr/bin/python #ssh import paramiko import sys,os host='127.0.0.1' user = 'whl' password = ' s = ...
- c++ list 合并list
1.参考 http://www.cplusplus.com/reference/list/list/ 2.合并 主要有两个函数:splice()和merge()splice()有三种调用形式:第一种: ...
- solr 5.2.1 tomcat 7 配置过程笔记
因为这个是新版,网上很少这个配置文档,看网上其他的教程弄了很多次,都没有成功,幸亏有这个链接的文档, 才迅速的配置成功,其实是比以前简洁了.因为我的在 linux 上面安装,不方便截图,直接复制修改了 ...
- HBase学习之深入理解Memstore-6
MemStore是HBase非常重要的组成部分,深入理解MemStore的运行机制.工作原理.相关配置,对HBase集群管理以及性能调优有非常重要的帮助. HBase Memstore 首先通过简 ...
- motion移植
一. 支持ffmpeg功能(使能motion中的视频编码功能)支持视频采集 —> ffmpeg不支持 —host 1. mkdir _install 2. ./configure —pref ...
- JAVA语言基础内部测试题(50道选择题)
JAVA语言基础内部测试题 选择题(针对以下题目,请选择最符合题目要求的答案,针对每一道题目,所有答案都选对,则该题得分,所选答案错误或不能选出所有答案,则该题不得分.)(每题2分) 没有注明选择几项 ...
- 超全面的JavaWeb笔记day22<文件上传>
文件上传概述 1 文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢. 2 文件上传对页面的要求 上传文件的要求比较多,需要记一下: 1. 必须使用 ...
- HTML的框架结构
<html> <head> <title>HTML的框架结构</title> </head> <frameset frameborde ...