multithreading - Python threads making them take 100% of my cpu -


python threads making them take 100% of cpu

all,

how make script take 100% of cpu? if post bad please explain why! appreciated.

import threading import sys  def isprime(number):     # isprime check if int prime     if not isinstance(number,int):         #check if number int         raise exception("please enter int. function: isprime.")     #create array of numbers check     rangeofnumbers=range(1,number+1,1)     #count of how many multiplacations if prime number 2     multiplicationcount=0     #tow loops loop through possibilities     n1 in rangeofnumbers:         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 python python 3.")     number=0     while true:         threads=[]         in range(100):             number+=1             thread=threading.thread(target=isprime,args=[number])             thread.start()             threads=[]             threads.append(thread)         thread in threads:             thread.join() 

isprime not no io or other operation potentially relinquish cpu (except print). therefore consumes 100% of one cpu core. since enough such jobs kicked of, measurable cpu usage should stay @ 100% of 1 core. note that, since python has additional limitation 1 thread can execute bytecode @ same time (referred global interpreter lock), no parallelism achieved here.

look python's multiprocessing module achieve real concurrency. spawns off new python processes, allowing multiple primality tests execute @ same time.

lastly, code not wait threads

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

(this not intentional). means keep creating threads in infinite loop, wait 1 of them finish. going run out of memory @ point. more catastrophic if python had real threading, though ...


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -