Python线程将项累积到集合中

2024-06-23 20:11:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有线程添加项目,比如说一个全球成功的名单

我知道线程通信应该通过Queue完成,但是在读取队列documentation时,没有函数来获得队列长度的确切计数

Queue.qsize() Return the approximate size of the queue. Note, qsize()

0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.

我也试过len(queue),但不起作用:

>>> import Queue
>>> q = Queue.Queue()
>>> q.put(1)
>>> q.put(2)
>>> len(q)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Queue instance has no attribute '__len__'

我也读过关于使用List的文章,但是我don't have definite answer是否会损坏数据

我现在唯一能想到的方法就是运行queue.get(),直到queue为空,然后转换成一个列表。有更好的选择吗


Tags: the项目getlenthat队列queueput
1条回答
网友
1楼 · 发布于 2024-06-23 20:11:25

qsize没有给出这些保证的原因是,在调用.qsize().get()之间,其他线程可能会插入一个元素。除此之外,您应该使用qsize。它将在呼叫时为您提供确切的队列大小。“近似”一词在这里的意思是,经过那一刻的呼吁大小不再保证是相同的。但是,当处理访问共享数据结构的线程时,无论结构是什么,都会遇到相同的问题

相关问题 更多 >

    热门问题