线程队列

1 基本语法和用法

  1. put 往线程队列里防止,超过队列长度,直接阻塞
  2. get 从队列中取值,如果获取不到,直接阻塞
  3. put_nowait: 如果放入的值超过队列长度,直接报错(linux)
  4. get_nowait: 如果获取的值已经没有了,直接报错

(1) queue 先进先出

from queue import Queue
q = Queue()
q.put(11)
q.put(22)
print(q.get())
print(q.get_nowait())

执行

[root@node10 python]# python3 test.py
11
22

直接报错

from queue import Queue
q = Queue()
q.put(11)
q.put(22)
print(q.get())
print(q.get_nowait())
print(q.get_nowait())

执行

指定队列长度

from queue import Queue
q2 = Queue(2)
q2.put(33)
q2.put(44)
q2.put(55)

直接阻塞

使用put_nowait报错

LifoQueue 后进先出

数据结构中,栈队列的一种储存顺序

from queue import LifoQueue
lq = LifoQueue()
lq.put(55)
lq.put(66)
print(lq.get())
print(lq.get())

执行

[root@node10 python]# python3 test.py
66
55

PriorityQueue 按照优先级顺序排列

  1. 默认按照数字大小排序,然后会按照ascii编码在从小到大排序
  2. 先写先排,后写后排
from queue import PriorityQueue
pq = PriorityQueue()
pq.put( (12,"John") )
pq.put( (6,"Jim") )
pq.put( (19,"Tom") )
pq.put( (8,"Lucy") ) print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())

执行

[root@node10 python]# python3 test.py
(6, 'Jim')
(8, 'Lucy')
(12, 'John')
(19, 'Tom')

当数字一样  按照ascsi值

from queue import PriorityQueue
pq = PriorityQueue()
pq.put( (12,"John") )
pq.put( (6,"Jim") )
pq.put( (19,"Tom") )
pq.put( (19,"Lucy") ) print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())

执行

[root@node10 python]# python3 test.py
(6, 'Jim')
(12, 'John')
(19, 'Lucy')
(19, 'Tom')

单独一个元素,必须放同一种类型

from queue import PriorityQueue
pq = PriorityQueue()
pg = PriorityQueue()
pg.put(13)
pg.put(18)
pg.put(3)
print(pg.get())
print(pg.get())
print(pg.get())

执行

[root@node10 python]# python3 test.py
3
13
18

如果不同类型

from queue import PriorityQueue
pq = PriorityQueue()
pg = PriorityQueue()
pg.put(13)
pg.put(18)
pg.put(3)
pg.put("sdfsdf")
print(pg.get())
print(pg.get())
print(pg.get())

执行

字符串类型

from queue import PriorityQueue
pg1 = PriorityQueue()
pg1.put("ab")
pg1.put("cc")
print(pg1.get())
print(pg1.get())

执行

[root@node10 python]# python3 test.py
ab
cc

2 新版进程池,线程池

进程池 允许cpu并行

执行一个进程,如果使用了进程池,是要控制进程并行数量

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os,time
def func(i):
print ("process:",i,os.getpid())
time.sleep(3)
print ("process:end")
return 6666
# 创建进程池对象,8是代表最大8个进程,ProcessPoolExecutor 后面的参数默认是cpu的最大逻辑处理器核心数.
p = ProcessPoolExecutor(8)
#异步触发进程,res 接收的是对象,这个对象可以通过result()来获取返回值
res = p.submit(func,1)
#获取进程任务的返回值
res2 = res.result()
#shutdown,等待所有子进程执行完毕之后,在向下执行,类似于join
p.shutdown() print("主进程执行完毕")

执行

[root@node10 python]# python3 test.py
process: 1 42441
process:end
主进程执行完毕

执行多个进程,如果使用了进程池,是要控制进程并行数量

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os,time
def func(i):
print ("process:",i,os.getpid())
time.sleep(3)
print ("process:end")
return 6666
# 创建进程池对象
p = ProcessPoolExecutor(8)
#异步触发进程,res 接收的是对象,这个对象可以通过result()来获取返回值
for i in range(12):
res = p.submit(func,i)
#获取进程任务的返回值
res2 = res.result()
#shutdown,等待所有子进程执行完毕之后,在向下执行,类似于join
p.shutdown() print("主进程执行完毕")

执行

[root@node10 python]# python3 test.py
process: 0 42457
process: 1 42458
process: 2 42459
process: 3 42460
process: 4 42461
process: 5 42462
process: 6 42463
process: 7 42464
process:end
process:end
process:end
process: 8 42463
process: 9 42457
process: 10 42459
process:end
process: 11 42462
process:end
process:end
process:end
process:end
process:end
process:end
process:end
process:end
主进程执行完毕

3 线程池

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import current_thread as cthread
import os,time
def func(i):
print("thread",i,cthread().ident)
time.sleep(3)
print("thread %s end %s"%(i)) #创建线程池。括号里面可以指定并发的线程数
tp = ThreadPoolExecutor(4)
for i in range(20):
tp.submit(func,i)
tp.shutdown()
print("主线程执行结束。。。")

执行

[root@node10 python]# python3 test.py
thread 0 140712745903872
thread 1 140712737511168
thread 2 140712658073344
thread 3 140712649680640
thread 4 140712745903872
thread 5 140712658073344
thread 6 140712737511168
thread 7 140712649680640
thread 8 140712737511168
thread 9 140712658073344
thread 10 140712745903872
thread 11 140712649680640
thread 12 140712737511168
thread 13 140712745903872
thread 14 140712658073344
thread 15 140712649680640
thread 16 140712745903872
thread 17 140712737511168
thread 18 140712649680640
thread 19 140712658073344
主线程执行结束。。。

4 GIL锁

一个进程中的多条线程同一时间只能被一个cpu执行,不能实现并行操作.
想要解决:更换Jpython 或者 PyPy解释器
为什么加锁:
python是解释性语言,编译一行,就执行一行,不能提前规划系统资源,进行全局分配,根本原因是历史遗留问题.
程序分为两大类:

  • 计算密集型程序,通过c语言改写python部分模块来实现
  • io密集型程序,类似于python_web 运维,数据分析 都可以使用

线程池的返回值

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import current_thread as cthread
import os,time
def func(i):
#获取当前线程号
print("thread",i,cthread().ident)
time.sleep(1)
#返回线程号,获取返回值,会加阻塞,无需shutdown
return cthread().ident #创建线程池。括号里面可以指定并发的线程数
tp = ThreadPoolExecutor(6)
lst = []
setvar = set()
for i in range(12):
#异步出发
res = tp.submit(func,i)
lst.append(res)
for i in lst:
#获取该进程对象的返回值
print (i.result())
    #塞到集合里面,可以去重,验证
setvar.add(i.result())
#打印所有的线程号
print (setvar)
print("主线程执行结束。。。")

执行

[root@node10 python]# python3 test.py
thread 0 140423614576384
thread 1 140423606183680
thread 2 140423597790976
thread 3 140423589398272
thread 4 140423581005568
thread 5 140423572612864
thread <Future at 0x7fb6f7ad4b70 state=running> 140423597790976
thread <Future at 0x7fb6f7ad4b70 state=running> 140423572612864
thread <Future at 0x7fb6f7ad4b70 state=running> 140423589398272
thread <Future at 0x7fb6f7ad4b70 state=running> 140423606183680
thread <Future at 0x7fb6f7ad4b70 state=running> 140423581005568
thread <Future at 0x7fb6f7ad4b70 state=finished returned int> 140423614576384
140423614576384
140423606183680
140423597790976
140423589398272
140423581005568
140423572612864
140423597790976
140423572612864
140423589398272
140423606183680
140423581005568
140423614576384
{140423614576384, 140423606183680, 140423581005568, 140423597790976, 140423589398272, 140423572612864}
主线程执行结束。。。

5 map返回迭代器

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os,time
from threading import current_thread as cthread
def func(i):
time.sleep(0.2)
print("thread",i,cthread().ident)
print("thread .. end %s" % (i))
return "*" * i tp = ThreadPoolExecutor(5)
it = tp.map(func,range(20))
tp.shutdown()
print("<===>")
from collections import Iterator
res = isinstance(it,Iterator)
print(res)
print(list(it)) # "1234567"
# it = map(int,"1234567")
# print(list(it))

执行

[root@node10 python]# python3 test.py
thread 0 140381751781120
thread .. end 0
thread 2 140381734995712
thread .. end 2
thread 1 140381743388416
thread .. end 1
thread 3 140381726603008
thread .. end 3
thread 4 140381718210304
thread .. end 4
thread 5 140381751781120
thread 6 140381734995712
thread .. end 5
thread .. end 6
thread 9 140381718210304
thread 8 140381726603008
thread .. end 8
thread 7 140381743388416
thread .. end 7
thread .. end 9
thread 14 140381718210304
thread .. end 14
thread 10 140381751781120
thread .. end 10
thread 11 140381734995712
thread .. end 11
thread 13 140381743388416
thread .. end 13
thread 12 140381726603008
thread .. end 12
thread 15 140381718210304
thread .. end 15
thread 19 140381726603008
thread .. end 19
thread 16 140381751781120
thread .. end 16
thread 18 140381743388416
thread .. end 18
thread 17 140381734995712
thread .. end 17
<===>
True
['', '*', '**', '***', '****', '*****', '******', '*******', '********', '*********', '**********', '***********', '************', '*************', '**************', '***************', '****************', '*****************', '******************', '*******************']

045.Python线程队列的更多相关文章

  1. python 线程队列PriorityQueue(优先队列)(37)

    在 线程队列Queue / 线程队列LifoQueue 文章中分别介绍了先进先出队列Queue和先进后出队列LifoQueue,而今天给大家介绍的是最后一种:优先队列PriorityQueue,对队列 ...

  2. python 线程队列LifoQueue-LIFO(36)

    在 python线程队列Queue-FIFO  文章中已经介绍了 先进先出队列Queue,而今天给大家介绍的是第二种:线程队列LifoQueue-LIFO,数据先进后出类型,两者有什么区别呢? 一.队 ...

  3. python线程队列Queue-FIFO(35)

    之前的文章中讲解很多关于线程间通信的知识,比如:线程互斥锁lock,线程事件event,线程条件变量condition 等等,这些都是在开发中经常使用的内容,而今天继续给大家讲解一个更重要的知识点 — ...

  4. python 线程队列、线程池、全局解释器锁GIL

    一.线程队列 队列特性:取一个值少一个,只能取一次,没有值的时候会阻塞,队列满了,也会阻塞 queue队列 :使用import queue,用法与进程Queue一样 queue is especial ...

  5. python线程+队列(queue)

    ---恢复内容开始--- python的线程学习 用处 pocpiliang脚本的编写 函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程.语法如下: _thr ...

  6. python线程池ThreadPoolExecutor(上)(38)

    在前面的文章中我们已经介绍了很多关于python线程相关的知识点,比如 线程互斥锁Lock / 线程事件Event / 线程条件变量Condition 等等,而今天给大家讲解的是 线程池ThreadP ...

  7. python全栈开发 * 线程队列 线程池 协程 * 180731

    一.线程队列 队列:1.Queue 先进先出 自带锁 数据安全 from queue import Queue from multiprocessing import Queue (IPC队列)2.L ...

  8. Python之线程 3 - 信号量、事件、线程队列与concurrent.futures模块

    一 信号量 二 事件 三 条件Condition 四 定时器(了解) 五 线程队列 六 标准模块-concurrent.futures 基本方法 ThreadPoolExecutor的简单使用 Pro ...

  9. Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就绪,挂起,运行) ,***协程概念,yield模拟并发(有缺陷),Greenlet模块(手动切换),Gevent(协程并发)

    Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就 ...

随机推荐

  1. 四单元总结&OO总结

    目录 本单元架构总结 第一次作业 第二次作业 第三次作业 架构设计总结 第一单元 第二单元 第三单元 对测试演进 课程收获 改进建议 线上学习体验 本单元架构总结 第一次作业 第一次作业按照UML正常 ...

  2. 数据结构☞二叉搜索树BST

    二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它可以是一棵空树,也可以是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值: 若它 ...

  3. 现代操作系统原书第3版.mobi

    电子书资源:现代操作系统原书第3版 书籍简介   本书是操作系统领域的经典之作,与第2版相比,增加了关于Linux.Windows Vista和Symbian操作系统的详细介绍.书中集中讨论了操作系统 ...

  4. Django中的CBV视图

    Web 开发是一项无聊而且单调的工作,特别是在视图功能编写方面更为显著.为了减少这种痛苦,Django植入了视图类这一功能,该功能封装了视图开发常用的代码,无须编写大量代码即可快速完成数据视图的开发, ...

  5. 浅谈跨域问题,CORS跨域资源共享

    1,何为跨域? 在理解跨域问题之前,你先要了解同源策略和URL,简单叙述: 1)同源策略 三同:协议相同,域名相同,端口相同: 目的:保证用户信息安全,防止恶意网站窃取数据.同源策略是必须的,否则co ...

  6. Mybatis的简单增删改查

    刚开始学习Mybatis可以先看下官方文档,MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis避免了几乎所有的JDBC代码和手工设置参数以及抽取结果集.MyBat ...

  7. 病毒木马查杀实战第016篇:U盘病毒之逆向分析

    比对脱壳前后的程序 我们这次所要研究的是经过上次的脱壳操作之后,所获取的无壳病毒样本.其实我们这里可以先进行一下对比,看看有壳与无壳的反汇编代码的区别.首先用IDA Pro载入原始病毒样本: 图1 可 ...

  8. 基于frida框架Hook native中的函数(1)

    作者:H01mes撰写的这篇关于frida框架hook native函数的文章很不错,值得推荐和学习,也感谢原作者. 0x01 前言 关于android的hook以前一直用的xposed来hook j ...

  9. 使用SSH端口做端口转发以及反向隧道

    目录 SSH做本地端口转发 SSH做反向隧道(远程端口转发) 用autossh建立稳定隧道 SSH开启端口转发需要修改 /etc/ssh/sshd_config配置文件,将 GatewayPorts修 ...

  10. 使用 Azure Container Registry 储存镜像

    Azure Container Registry(容器注册表)是基于 Docker Registry 2.0规范的托管专用 Docker 注册表服务. 可以创建和维护 Azure 容器注册表来存储与管 ...