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