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