Python 多线程算法将队列缩减为一个元素,但队列必须清空中间程序
我想构造一个算法,将队列缩减为一个元素,但可能(暂时)清空队列。我试图用一个多数字gcd算法来实现这一点,但它根本不起作用。我怀疑这个程序带有while循环,但我不确定如何修复它 任何帮助都将不胜感激。我是编程新手,如果这是一个太基本的问题,我深表歉意Python 多线程算法将队列缩减为一个元素,但队列必须清空中间程序,python,multithreading,queue,Python,Multithreading,Queue,我想构造一个算法,将队列缩减为一个元素,但可能(暂时)清空队列。我试图用一个多数字gcd算法来实现这一点,但它根本不起作用。我怀疑这个程序带有while循环,但我不确定如何修复它 任何帮助都将不胜感激。我是编程新手,如果这是一个太基本的问题,我深表歉意 import threading import Queue import time, random #Worker Class class Worker(threading.Thread): def __init__(self, que
import threading
import Queue
import time, random
#Worker Class
class Worker(threading.Thread):
def __init__(self, queue, flag):
self.__queue = queue
self.__flag = flag
threading.Thread.__init__(self)
def run(self):
while (queue.qsize() > 1):
a = self.__queue.get()
b = self.__queue.get()
#Worker task
g = gcd(a, b)
if g == 1:
flag = False
queue.put(g)
def quit(self):
return
#gcd algorithm
def gcd(a, b):
while b:
a, b = b, a%b
return a
#kill all workers
def killall(workers):
for worker in workers:
worker.quit()
#queue starts empty
queue = Queue.Queue(0)
#input thread number
WORKERS = int(raw_input("Type in the number of threads (int > 0):"))
#input list length
k = int(raw_input("Length of integer list (int > 0):"))
#random list of integers generated
list = [random.randint(1,1000) for i in range(k)]
while (len(list)):
queue.put(list.pop())
#list of workers
wrkrs = []
#flag to kill if 1 is found
flag = True
#Master function
for i in range(WORKERS):
w = Worker(queue, flag)
wrkrs.append(w)
w.start()
#kill process if 1 is found
if flag == False:
killall(w)
print "gcd is: 1"
#if this worked, answer would be the only remaining element
if queue.qsize() == 1:
print "gcd is:", queue.get()
像这样试图让多个线程从队列中删除“半个作业”是不安全的。您将遇到这样的问题:两个线程各有一个数字,并且两个线程都无法计算GCD。而且,检查队列的大小几乎从来都不安全。啊!好啊您建议我用两个元素字符串构建队列吗?问题是“半个作业”是工作线程的自然输出。我建议让一个线程通过第二个队列接收输出,并将它们组合成两个元素元组供工作人员使用。这个线程可以跟踪它已经组装了多少元组,以及它希望组装多少元组,这样它就可以知道什么时候到最后的GCD了。有意义。谢谢你的帮助。