1

这些线程中的每一个都在不同的数据对象列表中搜索序列号。如果找到它,它会将对象放入队列中。序列号是唯一的。

q = Queue.Queue(10)
thread_list = []
for i in range(0, 10):
   t = Thread(serial)
   thread_list.append(t)
   t.start()

而不是等待所有线程完成:

for t in thread_list:
    t.join()

当找到它正在寻找的序列号时,有什么方法可以停止所有线程?并考虑到它可能找不到序列号并且队列将保持为空的可能性?

4

1 回答 1

1

简单的方法是使用队列...在您的线程运行器类中(我假设串行是)

class FindSerial(Thread):
    def __init__(self, serial, queue):
         this.serial = serial
         this.queue  = queue
         super(FindSerial, self).__init__()

    def run(self):
        .... 
        while LOOKING_FOR_SERIAL:
            if not self.queue.empty():
                  return
        ....

 ...
 for i in range(0, 10):
     t = FindSerial(serial, q)
 ...

现在通过检查队列是否通过循环,您可以检查另一个线程是否找到了您正在寻找的对象,如果找到了,那么您只需从 run 方法返回,这将允许 join() 获得线。

注意:我可能只会通过循环检查空的 N 次迭代,以避免大量的锁争用。

于 2012-06-19T15:32:29.297 回答