Python线程使它们占用我的cpu的100%

时间:2014-08-18 17:12:08

标签: multithreading python-3.x

Python线程使它们占用我的cpu的100%

所有

如何让这个脚本占用我的cpu 100%?如果这篇文章不好请解释原因!任何帮助将不胜感激。

import threading
import sys

def isPrime(number):
    # isPrime is to check if a int is Prime
    if not isinstance(number,int):
        #check if number is a int
        raise Exception("Please enter a int. Function: isPrime.")
    #create array of numbers to check
    rangeOfNumbers=range(1,number+1,1)
    #count of how many multiplacations if it is a prime number it would be 2
    multiplicationCount=0
    #tow for loops to loop through all possibilities
    for n1 in rangeOfNumbers:
        for n2 in rangeOfNumbers:
            if (n1*n2==number):
                multiplicationCount +=1
    if (multiplicationCount==2):
        print(number)
        return True
    else:
        return False




if __name__ == "__main__":
    if not sys.version_info[0] == 3:
        raise Exception("Please Upgrade or Downgrade your python to python 3.")
    number=0
    while True:
        threads=[]
        for i in range(100):
            number+=1
            thread=threading.Thread(target=isPrime,args=[number])
            thread.start()
            threads=[]
            threads.append(thread)
        for thread in threads:
            thread.join()

1 个答案:

答案 0 :(得分:0)

isPrime没有IO或其他可能放弃CPU的操作(print除外)。因此,它消耗了100%的一个 CPU内核。由于足够的这样的工作被踢,可测量的CPU使用率应该保持在一个核心的大约100%。请注意,由于Python具有额外的限制,即只有一个线程可以同时执行字节码(称为Global Interpreter Lock),因此不会实现并行性。

Look into Python's multiprocessing module to achieve real concurrency.它产生了新的Python进程,因此允许多个素数测试同时执行。

最后,您的代码没有正确等待所有线程

while True:
    threads=[]
    for i in range(100):
        number+=1
        thread=threading.Thread(target=isPrime,args=[number])
        thread.start()
        threads=[] # threads being reset here!
        threads.append(thread)
    for thread in threads:
        thread.join()

(这可能不是故意的)。这意味着你在无限循环中继续创建线程,但只等待其中一个完成。这会让你在某些时候失去记忆。如果Python有真正的线程,那将会更具灾难性,但是......