# 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. # In order to make it possible to return a value to the main code with multiprocessing, I needed to use # the Value class, so this code is not really set up to work for both threading and multiprocessing. # from threading import Thread as Worker from multiprocessing import Process as Worker from multiprocessing import Value import time class PrimeCounter(Worker): def __init__ (self, s, e, chunk_stride, chunk_size, shared_count): super().__init__() self.begin = s self.extent = e self.chunk_stride = chunk_stride self.chunk_size = chunk_size self.count = 0 self.shared_count = shared_count # this one is visible after the process is over. 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 ) for offset in range( self.begin, self.begin + self.extent, self.chunk_stride ): for i in range (offset, offset+self.chunk_size): if self.is_prime(i): self.count += 1 #print( "found",self.count,"primes", self.getCount() ) self.shared_count.value = self.count return 0 def getCount (self): return self.count def main (): N = 100000 #N = 100 count1 = Value('i') count2 = Value('i') count0 = Value('i') pc1 = PrimeCounter(0, N, 200, 100, count1) pc2 = PrimeCounter(100, N, 200, 100, count2) pc3 = PrimeCounter(0, N, N, N, count0) t1 = time.time() pc1.start() pc2.start() pc1.join() pc2.join() t2 = time.time() # need to use Value's to get the value from the process print("2 thread count ", count1.value + count2.value, " primes") print("time is ", t2 - t1) t1 = time.time() pc3.start() pc3.join() t2 = time.time() print("1 thread count ", count0.value, " primes") print("time is ", t2 - t1) if __name__ == "__main__": main()