队列特性:先进先出(FIFO)——先进队列的元素先出队列。来源于我们生活中的队列(先排队的先办完事)。
Queue模块最常与threading模块一起构成生产-消费者模型,提供了一个适用于多线程编程的先进先出的数据结构,即队列。
该模块源码中包含5个类:
其中,Empty和Full是两个异常类,当队列的Queue.get(block=0)或者调用get_nowait()时,如果队列为空,则抛EmptyException异常。
同理,当队列的Queue.put(block=0)或者调用put_nowait()时,如果队列为达到maxsize,则抛FullException异常。
其他三个类:
Queue类:典型的队列模型,FIFO先入先出。 class Queue.Queue(maxsize) maxsize为队列长度,指明了队列中能存放的数据个数的上限。一旦达到上限,插入会导致阻 塞,
直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。
LifoQueue类:继承自Queue,类似于堆栈,先入后出。 class Queue.LifoQueue(maxsize)
PriorityQueue类:继承自Queue,优先级队列,级别越低越先出来。 class Queue.PriorityQueue(maxsize)
所以,只要搞定Queue类,就基本搞定Queue模块。
Queue类中常用的方法:
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应
Queue.get([block[, timeout]]) 获取队列,timeout等待时间 ,调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。
Queue.get_nowait() 相当于Queue.get(False)
Queue.put(item)
写入队列,timeout等待时间 ,调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第 二个block为可选参数,默认为1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.task_done()
在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
Queue.join()
实际上意味着等到队列为空,再执行别的操作
一个小的练习实例:
#coding:utf-8 import random, threading, time import Queue ''' 实现了一个生产线程,用于往队列中添加随机数10个, 实现了一个消费线程,分别消耗奇数随机数和偶数随机数 ''' class producer(threading.Thread): def __init__(self,t_name,queue): threading.Thread.__init__(self,name=t_name) self.data = queue def run(self): for i in xrange(10): random_num = random.randint(1,99) print "%s : %s 生产了一个随机数\033[31;0m %d \033[0m放入队列中" % (time.ctime(),self.getName(),random_num) self.data.put(random_num) time.sleep(1) print "生产线程完成!!" class consumer(threading.Thread): def __init__(self,t_name,queue): threading.Thread.__init__(self,name=t_name) self.data = queue def run(self): while True: try: tmp_num = self.data.get(1,5) #定义超时时间5秒 if tmp_num%2 == 0: print "%s : %s 消耗了一个队列中的偶数随机数\033[31;0m %d \033[0m" % (time.ctime(),self.getName(),tmp_num) time.sleep(2) else: print "%s : %s 消耗了一个队列中的奇数随机数\033[31;0m %d \033[0m" % (time.ctime(), self.getName(), tmp_num) time.sleep(2) except: print "消费线程完成!!" #一旦到达超时时间5秒,会抛异常,break退出循环 break def main(): queue = Queue.Queue(0) pro = producer('Pro', queue) con = consumer('Con', queue) pro.start() con.start() pro.join() con.join() print 'All threads complete!!!' if __name__ == '__main__': main()
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

使用NumPy创建多维数组可以通过以下步骤实现:1)使用numpy.array()函数创建数组,例如np.array([[1,2,3],[4,5,6]])创建2D数组;2)使用np.zeros(),np.ones(),np.random.random()等函数创建特定值填充的数组;3)理解数组的shape和size属性,确保子数组长度一致,避免错误;4)使用np.reshape()函数改变数组形状;5)注意内存使用,确保代码清晰高效。

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增强可读性,和Boostsperformance.Shere'shore'showitworks:1)较小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

文章讨论了由于语法歧义而导致的Python中元组理解的不可能。建议使用tuple()与发电机表达式使用tuple()有效地创建元组。(159个字符)

本文解释了Python中的模块和包装,它们的差异和用法。模块是单个文件,而软件包是带有__init__.py文件的目录,在层次上组织相关模块。

文章讨论了Python中的Docstrings,其用法和收益。主要问题:Docstrings对于代码文档和可访问性的重要性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Atom编辑器mac版下载
最流行的的开源编辑器