Python3:如何非阻塞获取Queue中的item

非阻塞获取item:

1、设置get方法传入block=false,缺点是会抛异常

	from queue import Queue
	
	def get(self, block=True, timeout=None):
	    '''Remove and return an item from the queue.
	
	    If optional args 'block' is true and 'timeout' is None (the default),
	    block if necessary until an item is available. If 'timeout' is
	    a non-negative number, it blocks at most 'timeout' seconds and raises
	    the Empty exception if no item was available within that time.
	    Otherwise ('block' is false), return an item if one is immediately
	    available, else raise the Empty exception ('timeout' is ignored
	    in that case).
	    '''
    

2、通过empty方法判断

    def empty(self):
        '''Return True if the queue is empty, False otherwise (not reliable!).

        This method is likely to be removed at some point.  Use qsize() == 0
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can grow before the result of empty() or
        qsize() can be used.

        To create code that needs to wait for all queued tasks to be
        completed, the preferred technique is to use the join() method.
        '''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
QueuePython的一个模块,用于在多个线程或进程之间进行数据交换。通过Queue,可以实现线程/进程之间的安全通信和数据共享。下面是一些关于Queue的用法: 1. 创建Queue对象: ``` from Queue import Queue q = Queue(maxsize=0) ``` maxsize参数指定队列的最大长度,0表示队列长度无限制。 2. 向队列添加元素: ``` q.put(item) ``` 使用put方法将item添加到队列。 3. 从队列获取元素: ``` q.get() ``` 使用get方法从队列获取一个元素,并将其从队列移除。 4. 判断队列是否为空: ``` q.empty() ``` 返回True表示队列为空,False表示队列不为空。 5. 判断队列是否已满: ``` q.full() ``` 返回True表示队列已满,False表示队列未满。 6. 获取队列的大小: ``` q.qsize() ``` 返回队列元素的个数。 7. 阻塞方式获取队列的元素: ``` q.get(block=True, timeout=None) ``` 如果队列为空,block参数为True(默认值),则get方法将会阻塞直到队列有可用元素或者超时。timeout参数指定等待时间。 8. 非阻塞方式获取队列的元素: ``` q.get(block=False) ``` 如果队列为空,将立即抛出Empty异常。 9. 完成任务信号: ``` q.task_done() ``` 在完成一项工作后,调用task_done方法告诉队列该任务已经处理完毕。 10. 等待队列为空: ``` q.join() ``` join方法实际上意味着等到队列为空,再执行别的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值