Language

Multithreading & Multiprocessing · Lesson 55 of 56

Factorial with Multiprocessing

Source: 16-Multithreading and Multiprocessing/factorial_multi_processing.py

Start here — no coding background needed

What you will learn

Split heavy math across cores — example: factorial chunks.

In simple words

Divide work, each process computes part, combine results.

Do many tasks at once — advanced; understand ideas first, code locally later.

Easy example — try this first

Easy example — run this first. Change values and press Run again.

Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference notes (from full bootcamp)

Optional — deeper detail for when you are ready

Reference script from the bootcamp repo. Read the code below; run a simplified version in the playground when marked runnable.

Example HCL
HCL
'''
Real-World Example: Multiprocessing for CPU-bound Tasks
Scenario: Factorial Calculation
Factorial calculations, especially for large numbers, 
involve significant computational work. Multiprocessing 
can be used to distribute the workload across multiple 
CPU cores, improving performance.

'''

import multiprocessing
import math
import sys
import time

# Increase the maximum number of digits for integer conversion
sys.set_int_max_str_digits(100000)

## function to compute factorials of a given number 

def computer_factorial(number):
    print(f"Computing factorial of {number}")
    result=math.factorial(number)
    print(f"Factorial of {number} is {result}")
    return result

if __name__=="__main__":
    numbers=[5000,6000,700,8000]

    start_time=time.time()

    ##create a pool of worker processes
    with multiprocessing.Pool() as pool:
        results=pool.map(computer_factorial,numbers)

    end_time=time.time()

    print(f"Results: {results}")
    print(f"Time taken: {end_time - start_time} seconds")

Browser practice only — full example needs Python on your computer (files, Flask, threads, etc.).

Practice test — try yourself

Write code, press Check. Wrong answer shows the correct code to copy & run.

You learned "Factorial with Multiprocessing". Use print() to show: Done: Factorial with Multiprocessing

Hint: Use one print() with the exact text.

Python