多线程算法将队列稀疏到一个元素,但队列必须为空中程序

时间:2016-02-11 18:39:44

标签: python multithreading queue

我想构建一个算法,将队列缩小到一个元素,但可以(暂时)清空队列。我尝试使用多编号gcd算法实现它,但它根本不起作用。我怀疑该程序是使用while循环,但我不知道如何解决它。

任何帮助将不胜感激。我是编程的新手,如果这是一个非常基本的问题,请道歉。

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()

0 个答案:

没有答案