我有一个程序来检查五个数字是否为素数,但它无法正常工作

时间:2015-11-24 08:02:13

标签: python multithreading

我正在尝试创建一个程序,从用户接收2个数字,并使用不同的线程来测试每个,这是我到目前为止,我知道我很好,但我发现这个线程的东西非常困难

#!/usr/bin/python

import threading 

class PrimeNumber(threading.Thread): 
  def __init__(self, number): 
    threading.Thread.__init__(self) 
    self.Number = number

  def run(self): 
    counter = 2 
    while counter*counter < self.Number: 
      if self.Number % counter == 0: 
       print "%d is no prime number, because %d = %d * %d" % ( self.Number,      self.Number, counter, self.Number / counter) 
         return 
         counter += 1 
         print "%d is a prime number" % self.Number
threads = [] 
while True: 
input1 = long(raw_input("Enter first number: ")) 
if input < 1: 
    break 

thread1 = PrimeNumber(input1) 
threads += [thread1] 
thread1.start() 

input2 = long(raw_input("Enter second number: ")) 
if input < 1: 
    break 

thread2 = PrimeNumber(input2) 
threads += [thread2] 
thread2.start() 


for x in threads: 
x.join()

1 个答案:

答案 0 :(得分:0)

我对您的代码做了一些修改。

  1. 第二个输入也需要一个while循环。 break在循环之外没有意义。
  2. 我将您input1 < 1的{​​{1}}转换为input1 > 1,因为您希望在有有效输入时退出循环,而不是输入无效时。
  3. 我在第一个while循环中正确缩进了代码。
  4. 我将<thread>.start行移至for循环。
  5. 这就是现在的样子:

    import threading 
    
    class PrimeNumber(threading.Thread): 
        def __init__(self, number): 
            threading.Thread.__init__(self) 
            self.Number = number
    
        def run(self): 
            counter = 2 
            while counter*counter < self.Number: 
                if self.Number % counter == 0: 
                    print "%d is not a prime number, because %d = %d * %d" % ( self.Number,      self.Number, counter, self.Number / counter) 
                    return 
                counter += 1 
            print "%d is a prime number" % self.Number
    
    threads = [] 
    while True: 
        input1 = long(raw_input("Enter first number: ")) 
        if input1 > 1: 
            break 
    
    thread1 = PrimeNumber(input1) 
    threads += [thread1] 
    
    while True:
        input2 = long(raw_input("Enter second number: ")) 
        if input2 > 1: 
            break 
    
    thread2 = PrimeNumber(input2) 
    threads += [thread2] 
    
    
    for x in threads:
        x.start()
        x.join()
    

    你在问题​​标题中说你要检查五个号码。而不是复制你输入的特定代码段并再为它创建一个线程三次,把它放在for循环中,如下所示:

    threads = []
    for i in range(5):
        while True: 
            inputNum = long(raw_input("Enter first number: ")) 
            if inputNum > 1: 
                break 
    
        thread = PrimeNumber(inputNum) 
        threads += [thread]