我为了练习目的写了一个Python脚本,我在其中计算给定值的所有素数。但我遇到了一些不一致的错误。
首先是代码:
import datetime
import time
import threading
class myThread (threading.Thread):
def __init__(self, threadID, name, threadcounter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.threadcounter = threadcounter
def run(self):
delete_non_primes (self.threadcounter)
print ('This script outputs all primes until the given value. \nWhat value shall be calculated until? ')
maxval = int(input("Please enter the wanted value: "))
print ('Preparing...')
primes = []
primes.append(0)
primes.append(0)
primes.append(2)
i = 3
for i in range (3,maxval+1):
primes.append(i)
if primes[3]!=3:
import sys
sys.exit("An error occured.")
counter = 1
percent = 0
thread1 = myThread(1, "Thread-1 iniated", 0)
thread2 = myThread(2, "Thread-2 iniated", 0)
thread3 = myThread(3, "Thread-3 iniated", 0)
thread4 = myThread(4, "Thread-4 iniated", 0)
thread5 = myThread(5, "Thread-5 iniated", 0)
nr_of_threads = 0
def delete_non_primes ( prime ):
if prime != 0:
breaker = prime
while (breaker < maxval):
breaker = breaker +1
if primes[breaker] != 0:
if primes [prime] != 0:
if (primes[breaker] % primes[prime]) == 0:
primes[breaker] = 0
print ("Preparation done.")
print ("Calculating...")
start = datetime.datetime.now()
while (counter < maxval ):
if counter < maxval:
counter = counter +1
thread1 = myThread(1, "Thread-1", counter)
thread1.start()
if counter < maxval:
counter = counter +1
thread2 = myThread(2, "Thread-2", counter)
thread2.start()
if counter < maxval:
counter = counter +1
thread3 = myThread(3, "Thread-3", counter)
thread3.start()
if counter < maxval:
counter = counter +1
thread4 = myThread(4, "Thread-4", counter)
thread4.start()
if counter < maxval:
counter = counter +1
thread5 = myThread(5, "Thread-5", counter)
thread5.start()
thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()
#This time.sleep() seems to make the code consistent
time.sleep(0.05)
if (counter*100)//maxval > percent:
percent = (counter*100)//maxval
print (str(percent) + "%")
end = datetime.datetime.now()
time_needed = end-start
print("\nPrimes to the given max value:")
j = 0
val = 0
while (j <maxval):
j = j+1
if primes[j] != 0:
val = val+1
if val < 1000000:
valstr = str(val) + " "
if val < 100000:
valstr = valstr + " "
if val < 10000:
valstr = valstr + " "
if val < 1000:
valstr = valstr + " "
if val < 100:
valstr = valstr + " "
if val < 10:
valstr = valstr + " "
print ( str(valstr) + str(primes[j]))
print ("Time needed for calculation: " + str(time_needed))
print("All primes noted. Script ends.")
有时会出现错误
&#34;回溯(最近一次呼叫最后一次):
文件&#34; python&#34;,第58行,
RuntimeError:无法启动新线程&#34;
如果我不使用Time.Sleep(0.05) 它并不总是相同的线程,如果我使用它,我不会收到任何错误。由于这个脚本中有很多计算,没有这个声明会更好。