python - 多线程时队列冲突?

标签 python python-2.7

我试图建立一个非常简单的多线程模型,到目前为止它似乎可以工作。我的问题是我如何确定两个线程不会同时从队列中获取相同的值并给我重复?是否只有一些内置方法可以防止这种情况发生?我添加了一个延迟以尝试在每个线程从队列中获取值之间设置时间,这是必要的吗?

from Queue import Queue
from threading import Thread
import time

class myThread(Thread):
    def __init__(self,queue):
        Thread.__init__(self)
        self.queue = queue
    def run(self):       
        while True:                      
            time.sleep(0.0001)   #not sure if this is good enough to compensate for overlap in pulling the same value out of a queue         
            task = self.queue.get() #pull a number from the queue,
            if task != None:          
                out.append(task) #This will be where you        
            else:               
                break


queue = Queue()
out = []


for i in range(10):
    t = myThread(queue)
    t.start()
for i in range(100):
    queue.put(i)
print out

最佳答案

Queue 类实现锁定以防止这种情况发生,请参阅 http://docs.python.org/library/queue.html ,特别是:

It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

所以你不需要任何延迟,队列应该完全按照你的意愿工作。这就是它的目的(基本上):-)

关于python - 多线程时队列冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10807972/

相关文章:

python - 如何处理大量小部件的 QPropertyAnimation

python - 如何在 python 中为 chrome 的 webdriver 设置代理

python - 基于具有相同长度的 pandas.DataFrame 的 groupby 的 numpy.array 进行 Groupby

python-2.7 - 两个输入图像都必须在函数错误中具有 CV_8UC1

linux - GCC在centos上安装pyICU报错

python-2.7 - 在python的OpenCV中找到标有CornerHarris方法的Corners坐标

python - 如何用python获取特定颜色(RGB)的像素坐标[x,y]列表?

python - 如何将包含所有依赖项的 python 包安装到 Docker 镜像中?

Python 线程 - 让线程开始而不等待前一个线程完成

python - python 2.7 的 mod_python