在Python中使用队列时对象跳过队列的问题
现在我正在实现一个线程,它基本上会充当消费者。会有一个先进先出(FIFO)的队列,这个队列会被其他线程填充。问题是,我想添加一个特殊的条件,让某个项目完全跳过这个队列。
def EventThread (threading.Thread):
def __init__ (self, counter_object):
super (EventThread, self).__init__ ()
self.queue = Queue.Queue ()
self.priority = threading.Event ()
self.item = None
self.counter = counter.object
def add_to_queue (self, item):
self.queue.put (item)
def do_priority (self, item)
self.item = item
self.priority.set ()
# do something here to block until priority goes back
def run (self):
while True:
# Wait for open event slots
if not self.counter.has_slots ():
time.sleep (self.counter.next_slot ())
# Block until queue has something
item = self.queue.get (True)
# If priority is set we need to do that first
if self.priority.is_set ():
do_something_special (self.item)
self.priority.clear ()
else:
do_something (item)
# first if priority was set we lost the object
# second the thread blocks until the queue has an object, doesn't
# metter if priority has been set
这只是一些伪代码,用来说明我的观点。但是你可以看到这里有一些大问题。其实不需要担心计数器,因为只有这个线程会访问它。
我真正需要的是一种方法,让这个线程在等待时,直到要么优先级的项目发生变化,要么队列里有了新项目。我对多线程还比较陌生,所以不知道有没有适合我需求的对象或者有什么技巧可以做到这一点。
非常感谢任何能够提供帮助的人。