python线程安全的数据结构_PYTHON——多线程:队列Queue数据结构

本文介绍了Python中线程安全的数据结构——队列Queue,讲解了其在多线程中的作用,避免了数据不安全的问题。通过实例展示了Queue的创建、put和get方法的使用,以及FIFO、LIFO和优先级队列的类型。此外,还提供了两个多线程使用Queue的实例,包括生产者消费者模型的应用。
摘要由CSDN通过智能技术生成

1、队列模块简介

队列是一种数据结构,用于存放数据,类似列表。它是先进先出模式(FIFO模式),类似管道一般;

单线程不需要用到队列Queue,它主要用在多线程之间的,Queue称为多线程利器。

列表在多线程共享资源的话,与queue队列比较,主要表现为列表在多线程中,数据不安全。多个线程到列表中拿数据,可能拿到相同的数据。而多线程采用队列Queue作为共享资源的数据结构的话,不同线程从队列中取出(get())数据,能够保证数据的不同,这就是队列Queue的优势。这是因为队列内部本身就有一把锁,保证共享数据的安全。

队列中,存放系列任务,每个线程执行一个任务。

创建一个“队列”对象

import Queue

q = Queue.Queue(maxsize = 10)

Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。

将一个值放入队列中

q.put(10)

调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为

1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。

将一个值从队列中取出

q.get()

调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。

Python Queue模块有三种队列及构造函数:

1、Python Queue模块的FIFO队列先进先出。 class queue.Queue(maxsize)

2、LIFO类似于堆,即先进后出。 class queue.LifoQueue(maxsize)

3、还有一种是优先级队列级别越低越先出来。 class queue.PriorityQueue(maxsize)

此包中的常用方法(q = Queue.Queue()):

q.qsize() 返回队列的大小

q.empty() 如果队列为空,返回True,反之False

q.full() 如果队列满了,返回True,反之False

q.full 与 maxsize 大小对应

q.get([block[, timeout]]) 获取队列,timeout等待时间

q.get_nowait() 相当q.get(False)

非阻塞 q.put(item) 写入队列,timeout等待时间

q.put_nowait(item) 相当q.put(item, False)

q.task_done() 在完成一项工作之后,q.task_done() 函数向任务已经完成的队列发送一个信号

q.join() 实际上意味着等到队列为空,再执行别的操作

2、实例代码:

实例一:

importthreading,queuefrom time importsleepfrom random importrandintclassProduction(threading.Thread):defrun(self):whileTrue:

r=randint(0,100)

q.put(r)print("生产出来%s号包子"%r)

sleep(1)classProces(threading.Thread):defrun(self):whileTrue:

re=q.get()print("吃掉%s号包子"%re)if __name__=="__main__":

q=queue.Queue(10)

threads=[Production(),Production(),Production(),Proces()]for t inthreads:

t.start()

实例二:

#实现一个线程不断生成一个随机数到一个队列中(考虑使用Queue这个模块)#实现一个线程从上面的队列里面不断的取出奇数#实现另外一个线程从上面的队列里面不断取出偶数

importrandom,threading,timefrom queue importQueue#Producer thread

classProducer(threading.Thread):def __init__(self, t_name, queue):

threading.Thread.__init__(self,name=t_name)

self.data=queuedefrun(self):for i in range(10): #随机产生10个数字 ,可以修改为任意大小

randomnum=random.randint(1,99)print ("%s: %s is producing %d to the queue!" %(time.ctime(), self.getName(), randomnum))

self.data.put(randomnum)#将数据依次存入队列

time.sleep(1)print ("%s: %s finished!" %(time.ctime(), self.getName()))#Consumer thread

classConsumer_even(threading.Thread):def __init__(self,t_name,queue):

threading.Thread.__init__(self,name=t_name)

self.data=queuedefrun(self):while 1:try:

val_even= self.data.get(1,5) #get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒

if val_even%2==0:print ("%s: %s is consuming. %d in the queue is consumed!" %(time.ctime(),self.getName(),val_even))

time.sleep(2)else:

self.data.put(val_even)

time.sleep(2)except: #等待输入,超过5秒 就报异常

print ("%s: %s finished!" %(time.ctime(),self.getName()))break

classConsumer_odd(threading.Thread):def __init__(self,t_name,queue):

threading.Thread.__init__(self, name=t_name)

self.data=queuedefrun(self):while 1:try:

val_odd= self.data.get(1,5)if val_odd%2!=0:print ("%s: %s is consuming. %d in the queue is consumed!" %(time.ctime(), self.getName(), val_odd))

time.sleep(2)else:

self.data.put(val_odd)

time.sleep(2)except:print ("%s: %s finished!" %(time.ctime(), self.getName()))break

#Main thread

defmain():

queue=Queue()

producer= Producer('Pro.', queue)

consumer_even= Consumer_even('Con_even.', queue)

consumer_odd= Consumer_odd('Con_odd.',queue)

producer.start()

consumer_even.start()

consumer_odd.start()

producer.join()

consumer_even.join()

consumer_odd.join()print ('All threads terminate!')if __name__ == '__main__':

main()

实例三:注意:列表在线程中不安全

importthreading,time

li=[1,2,3,4,5]defpri():whileli:

a=li[-1]print(a)

time.sleep(1)try:

li.remove(a)except:print('----',a)

t1=threading.Thread(target=pri,args=())

t1.start()

t2=threading.Thread(target=pri,args=())

t2.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值