Skip to main content
 首页 » 编程设计

python之多线程时队列冲突

2025年05月04日22dudu

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

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.

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