Skip to content

Instantly share code, notes, and snippets.

@james-see
Created August 22, 2023 22:32
Show Gist options
  • Save james-see/a7aad6a70f122eeccc7f59fb91d3ed71 to your computer and use it in GitHub Desktop.
Save james-see/a7aad6a70f122eeccc7f59fb91d3ed71 to your computer and use it in GitHub Desktop.
multiprocessing example python prime factorization
import multiprocessing
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def prime_factors(n):
factors = []
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def factorize_worker(num, result_queue):
factors = prime_factors(num)
result_queue.put((num, factors))
def main():
nums_to_factorize = [555555555555, 1234567890123, 9876543210987, 123456789012345]
num_workers = multiprocessing.cpu_count() # Use the number of available CPU cores
result_queue = multiprocessing.Queue()
processes = []
for num in nums_to_factorize:
process = multiprocessing.Process(target=factorize_worker, args=(num, result_queue))
processes.append(process)
process.start()
for process in processes:
process.join()
results = []
while not result_queue.empty():
results.append(result_queue.get())
results.sort(key=lambda x: x[0]) # Sort results based on the original numbers
for num, factors in results:
print(f"Factors of {num}: {factors}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment