day34 线程池 协程
今日内容:
1. 线程的其他方法
2.线程队列(重点)
3.线程池(重点)
4.协程
1.线程的其他方法
语法:
Threading.current_thread() # 当前正在运行的线程对象的一个列表
GetName() # 获取线程名
Ident() 获取线程的ID
Threading.active_count() # 当前正在运行的线程数量
import threading
import time
from threading import Thread,current_thread def f1():
time.sleep(1)
print('子进程的名称',current_thread().getName()) # Thread-1
print(f'{i}号线程任务') if __name__=='__main__':
t1=Thread(target=f1,args=(2,))
t1.start()
print('主线程名称',current_thread().getName()) # MainThread
print('主线程ID',current_thread().ident) # 查看主线程ID
print(current_thread())
print(threading.enumerate()) #[<_MainThread(MainThread, started 6708)>,
<Thread(Thread-1, started 7848)>] print(threading.active_count()) #主线程和子线程的和
print('主线程结束')
2.线程队列(重点)
Put的数据是一个元组,元组的第一个参数是优先级数字,数字越小优先级越高,越先被get到被取出来,第二个参数是put进去的值,如果说优先级相同,那么值别忘了应该是相同的数据类型,字典不行
线程队列我们这里介绍3种:
import queue
1).先进先出队列 queue.Queue
import queue
q=queue.Queue(3)
q.put(1)
q.put(2)
print(q.qsize())# 查看当前队列的长度
q.put(3)
try:
q.put_nowait(4) # 和put效果一样,但是如果队列满了继续放它会报错
except exception:
print('队列满了,放不进去了')
print(q.full()) # 查看当前队列是否是满的 print(q.get())#1
print(q.get())#2
print(q.get())#3
print(q.get_nowait()) #和get效果一样,但是如果队列空了继续拿会报错
print(q.empty())# 查看当前队列是否是空的
2).先进后出队列 queue.LifoQueue
import queue q=queue.LifoQueue(3)
q.put(1)
q.put(2)
print(q.qsize())
q.put(3)
q.put_nowait(4)
print(q.full()) print(q.get())#3
print(q.get())#2
print(q.get())#1
print(q.empty()) #查看队列是否是空的
print(q.get_nowait())
3).优先级队列 queue.PriorrityQueue
q=queue.priorityQueue(3) q.put((2,'alex')) # 必须是元组
q.put((2,'大力')) #数据类型相同才能比较
q.put((-2,'666')) # 如果值里面的元素是int类型,如果这两个值大小,就先拿比较小的那个;如果这两个值大小相同,
那么比较的是下一个元素的第一个ascii码大小,小的优先被取出来
# 如果元素类型是字符串,那么依次比较每个字母的ascii的大小,小的被优先拿出来
# 字典不能比较
print(q.get())
print(q.get())
print(q.get())
3.线程池
from concurrent_futures import ThreadPoolExecutor,ProcessPoolExecutor
p=ThreadPoolExecutor(3) #默认线程的个数是cpu的个数 *5
p=ProcessPoolExecutor(3) #默认进程的个数是cpu的个数
p.map(f1,可迭代对象) # 异步执行
res=p.submit(f1,无敌传参,传什么都行) #异步提交任务
print(res.result()) #和get方法一样,如果没有结果,会等待,阻塞程序
Shutdown()# close+join ,锁定线程池,等待线程池中的所有已经提交的任务全部执行完毕
import time
from threading import current_thread
from concurrent.futures import ThreadPoolExecutor ,ProcessPoolExecutor def f1(n):
time.sleep(1)
print(f'{n}号子线程')
print('n') if __name__=='__main__':
tp=ThreadPoolExecutor(4)
re_list=[]
# 方法1
tp.map(f1,range(10)) # 异步提交任务,参数同样时任务名称,可迭代对象,不打乱顺序
# 方法2
for i in range(10):
res=tp.submit(f1,i,'baobao') # submit是给线程池异步提交任务,打乱顺序
re_list.append(res)
for el in re_list:
print(el.result())
print('主线程结束')
tp.shutdown() #主线程等待所有提交给线程池的任务,全部执行完毕 close + join
4.协程
生成器版协程:(有BUG)
import time
def f1():
for i in range(10):
time.sleep(1)
print('f1执行后的结果',i)
yield def f2():
g=f1()
for i in range(10):
time.sleep(1)
print('f2执行后的结果',i)
next(g) f1()
f2()
greenlet 版协程
import time
import greenlet
def f1(s):
print('第一次f1',s)
g2.switch('alex')# 切换到g2这个对象的任务去执行
time.sleep(0.4)
print('第二次f1',s)
g2.switch('baobao') def f2(s):
print('第一次f2',s)
g1.switch('wusir')
time.sleep(0.6)
print('第二次f2',s) g1=greenlet(f1)#实例化对象,并将任务名称作为参数传进去
g2=greenlet(f2)
g1.switch('zhu')# 执行g1对象的任务
gevent版真正的协程(真正意义上的协程,异步执行程序)
import gevent
from gevent import monkey;monkey.patch_all()
import time
import threading def f1():
print('第一次f1')
gevent.sleep(1)
print('第二次执行f1') def f2():
print('第一次执行f2')
gevent.sleep(1)
print('第二次执行f2') g1=gevent.spawn(f1)
g2=gevent.spawn(f2)
gevent.joinall([g1,g2]) # 相当于g1.join() g2.join()
print('主程序任务结束')
day34 线程池 协程的更多相关文章
- python全栈开发 * 线程队列 线程池 协程 * 180731
一.线程队列 队列:1.Queue 先进先出 自带锁 数据安全 from queue import Queue from multiprocessing import Queue (IPC队列)2.L ...
- Day037--Python--线程的其他方法,GIL, 线程事件,队列,线程池,协程
1. 线程的一些其他方法 threading.current_thread() # 线程对象 threading.current_thread().getName() # 线程名称 threadi ...
- python 线程(其他方法,队列,线程池,协程 greenlet模块 gevent模块)
1.线程的其他方法 from threading import Thread,current_thread import time import threading def f1(n): time.s ...
- 进程池线程池 协程 gvent 单线程实现并发套接字
1.基于多线程实现套接字服务端支持并发 服务端 from socket import * from threading import Thread def comunicate(conn): whil ...
- day 34 线程队列 线程池 协程 Greenlet \Gevent 模块
1 线程的其他方法 threading.current_thread().getName() 查询当前线程对象的名字 threading.current_thread().ident ...
- python并发编程-进程池线程池-协程-I/O模型-04
目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...
- 05网络并发 ( GIL+进程池与线程池+协程+IO模型 )
目录 05 网络并发 05 网络并发
- Queue、进程、线程、协程
参考博客地址 http://www.cnblogs.com/alex3714/articles/5230609.html 1.python GIL全局解释器锁 python调用的操作系统的原生线程,当 ...
- python中socket、进程、线程、协程、池的创建方式和应用场景
进程 场景 利用多核.高计算型的程序.启动数量有限 进程是计算机中最小的资源分配单位 进程和线程是包含关系 每个进程中都至少有一条线程 可以利用多核,数据隔离 创建 销毁 切换 时间开销都比较大 随着 ...
随机推荐
- 第 2 章 容器架构 - 006 - 容器 What, Why, How
What - 什么是容器? 容器: 容器是一种轻量级.可移植.自包含的软件打包技术,使应用程序可以在几乎任何地方以相同的方式运行. 开发人员在自己笔记本上创建并测试好的容器,无需任何修改就能够在生产系 ...
- Linux-Ubuntu16.0.4相关命令
1.更新软件源 sudo apt-get update 2.shell命令 基本格式:命令 [-选项] [-命令参数] ls #查看当前文件夹下的文件 ls -l XXXX #查看XXXX文件夹下的 ...
- nginx+php上传大文件配置
//nginx- //上传文件大小限制,需在nginx.conf中配置 'client_max_body_size' => '500M', //php- //允许上传文件大小的最大值,需在php ...
- learn python the hard way 习题18~25总结
定义函数和调用函数的语法 定义函数 形式: def functionName(p1,p2): statement other statement 需要注意: 紧跟者函数定义的代码是否使用了4个空格的缩 ...
- PHP的几种输出方式
请写出echo.print_r.print.var_dump .die之间的区别 echo 只能输出字符串等单一数据 不能输出数据类型 不能输出数组等多种数据 print() 只能输出字符串等单一 ...
- Windows下如何使用Heroku
1. 安装 进入https://devcenter.heroku.com/articles/heroku-cli#windows,选择对应版本安装 安装后使用heroku -v可检查版本号 2. 登陆 ...
- 『TensorFlow』SSD源码学习_其八:网络训练
Fork版本项目地址:SSD 作者使用了分布式训练的写法,这使得训练部分代码异常臃肿,我给出了部分注释.我对于多机分布式并不很熟,而且不是重点,所以不过多介绍,简单的给出一点训练中作者的优化手段,包含 ...
- const constptr 和引用的盲点(未解决)
#include<iostream> //const 和 引用的值必须初始化 //等号左侧是const或者const和引用,右侧可以是数字,普通变量-等号左侧是const和指针,右侧必须是 ...
- H5 DeviceMotionEvent 事件制作“摇一摇效果”
摇一摇”的效果制作主要依赖于H5的deviceMotionEvent事件 先讲怎么使用,具体的原理在后边补充 第一步:捕捉重力加速度 var acceleration = eventData.acce ...
- CacheManager.NET
Cache缓存在计算机领域是一个被普遍使用的概念.硬件中CPU有一级缓存,二级缓存, 浏览器中有缓存,软件开发中也有分布式缓存memcache, redis.缓存无处不在的原因是它能够极大地提高硬件和 ...