现在我正在实现一个基本上充当消费者的线程。将有一个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
这只是一些伪代码来详细说明我的观点。但是你可以看到那里有一些大问题。没有必要担心只有这个线程访问它的计数器。
我真正需要的是一些让线程阻塞的方法,直到 优先级项目切换或队列获取项目为止。我对多线程很陌生,所以我不知道任何符合我需要的对象或任何技巧来解决这个问题。
非常感谢能够提供帮助的任何人。