import threading
class PrimeNumber(threading.Thread):
def __init__(self, number):
threading.Thread.__init__(self)
self.Number = int(number)
def run(self):
counter = 2
while counter*counter <= self.Number:
if self.Number % counter == 0:
promptLock.acquire()
if(prompt):print()
print( "%d is not prime number" % ( self.Number) )
if(prompt):print("number: ",end="")
promptLock.release()
return
counter += 1
promptLock.acquire()
if(prompt): print()
print ("%d is a prime number" % self.Number)
#strange line
debug_line = 1
if(debug_line==1):
if(prompt):print("number: ",end="")
if(debug_line==2):
if(prompt):print("number: ")
promptLock.release()
threads = []
prompt=False
promptLock = threading.Lock()
def promptlocker():
global prompt
promptLock.acquire()
prompt = not prompt
promptLock.release()
while True:
promptlocker()
print("number: ",end="")
input1 = int(input())
promptlocker()
if input1 < 1:
break
thread = PrimeNumber(input1)
threads += [thread]
thread.start()
for x in threads:
x.join()
我正在使用此代码来测试python3中的线程
如果我输入输入1000000099999963然后55
因为第一次输入是漫长而耗时的
所以它将在新的线程中计算,然后会有提示要求新的输入,然后我们可以添加新的输入,如果它更容易计算,那么它很容易计算和打印。
然后当完成计算大数的线程时,它将打印其输出
所以现在我想要,如果代码要求一个数字,即提示 是那么我想打印&#34;数字:&#34;再次。
我希望输出为
number: 1000000099999963
number: 55
55 is not prime number
number:
1000000099999963 is a prime number
number:
但输出是
number: 1000000099999963
number: 55
55 is not prime number
number:
1000000099999963 is a prime number
当debug_line设置为1时,不知道为什么行
if(prompt):print("number: ",end="")
无效
如果我将debug_line设置为2,那么该行将起作用
if(prompt):print("number: ")
答案 0 :(得分:0)
你得到什么错误?
我将代码更改为在Python2.7中工作 这是我的代码:
import threading
class PrimeNumber(threading.Thread):
def __init__(self, number):
threading.Thread.__init__(self)
self.Number = int(number)
def run(self):
counter = 2
while counter*counter <= self.Number:
if self.Number % counter == 0:
promptLock.acquire()
if(prompt):print()
print( "%d is not prime number" % ( self.Number) )
if(prompt):
print "number: ",
promptLock.release()
return
counter += 1
promptLock.acquire()
if(prompt): print()
print ("%d is a prime number" % self.Number)
#strange line
debug_line = 1
if(debug_line==1):
if(prompt):print "number: ",
if(debug_line==2):
if(prompt):print "number: ",
promptLock.release()
threads = []
prompt=False
promptLock = threading.Lock()
def promptlocker():
global prompt
promptLock.acquire()
prompt = not prompt
promptLock.release()
while True:
promptlocker()
print "number: ",
input1 = int(input())
promptlocker()
if input1 < 1:
break
thread = PrimeNumber(input1)
threads += [thread]
thread.start()
for x in threads:
x.join()
我的输出:
number: 1000000099999963
number: 55
55 is not prime number
number: ()
1000000099999963 is a prime number
number:
如果您遇到print语句的问题,那么您可能想检查您的python版本。
if(prompt):print("number: ",end="")
以上行在Python2中引发了SyntaxError。它仅在Python3中受支持 Python2中的等效代码是:
if(prompt):print "number: ",
如果版本不是问题,那么您可能想检查此错误 Inconsistent use of tabs and spaces in indentation