# PrimeCounter.py # Python has multi-threading, but that doesn't take advantage of multiple cores because # of an underlying global interpreter lock (GIL) # multiprocessing is heavier (a new process is created). # the code below generates the correct answer for the threaded code, but only one processor is used # It does run multiple processes if we use multithreading, but getCount returns 0 at the end. I think # we would need to use a multiprocessing.Array to get information back to the main process. # from threading import Thread as Worker from multiprocessing import Process as Worker import time class PrimeCounter(Worker): def __init__ (self, s, e): super().__init__() self.begin = s self.extent = e self.count = 0 def is_prime (self, n): if (n < 2): return False if (n == 2): return True if (n % 2 == 0): return False for i in range (3, n, 2): if (n % i == 0): return False; return True def run (self): print( "running thread with pid", self.pid ) # won't work with multi-threading for i in range (self.begin, self.begin + self.extent): if self.is_prime(i): self.count += 1 print( "found",self.count,"primes", self.getCount() ) def getCount (self): return self.count def main (): N = 100000 #N = 100 pc1 = PrimeCounter(0, N//2) pc2 = PrimeCounter(N//2, N//2) pc3 = PrimeCounter(0, N) t1 = time.time() pc1.start() pc2.start() pc1.join() pc2.join() t2 = time.time() print("2 thread count ", pc1.getCount() + pc2.getCount(), " primes") print("time is ", t2 - t1) t1 = time.time() pc3.start() pc3.join() t2 = time.time() print("1 thread count ", pc3.getCount(), " primes") print("time is ", t2 - t1) if __name__ == "__main__": main()