Data in Time: Processes and Concurrency in Python🔄

When you run a Python program, it feels simple. You write code, press run, and something happens. But under the surface, your operating system is doing serious work. It creates processes, assigns memory, manages CPU time, and keeps everything isolated so programs don’t crash into each other.

In this article, we’ll break down processes, multiprocessing, threads, concurrency, queues, and the concurrent.futures module — all in a clear, practical way. No academic tone. Just real understanding.


Programs vs Processes

A program is just code stored on disk.

A process is what happens when that program runs.

When you execute a Python script:

  • The operating system creates a new process.

  • It assigns memory.

  • It gives CPU time.

  • It tracks file usage and network connections.🔎

  • It isolates it from other running programs.

This isolation is important. One process cannot directly interfere with another.

You can view running processes using:

  • Task Manager (Windows)

  • Activity Monitor (macOS)

  • top command (Linux)

Python can also inspect process information using the os module:

import os print(os.getpid()) # Process ID print(os.getcwd()) # Current working directory

Running Other Programs with subprocess

Sometimes your Python script needs to run another program.

That’s where the subprocess module comes in.

Example:

import subprocess output = subprocess.getoutput("date") print(output)

This runs a shell command and captures its output.

A safer version:

import subprocess result = subprocess.check_output(["date"]) print(result)

This avoids shell injection issues and returns output as bytes.

Use subprocess when:

  • You need to automate shell commands

  • You want to interact with system tools

  • You’re building automation scripts


Creating Multiple Processes with multiprocessing

Python allows you to create separate processes using the multiprocessing module.

Example:

from multiprocessing import Process def do_this(): print("Running task") if __name__ == "__main__": for _ in range(4): p = Process(target=do_this) p.start()

This creates four separate processes.

Each process:

  • Has its own memory space

  • Runs independently

  • Does not share variables automatically

If needed, you can stop a process:

p.terminate()

Understanding Concurrency

Computers wait for two main reasons:🫸⏳

1. I/O-Bound Tasks

Waiting for:

  • Disk reads

  • Network responses

  • Database queries

The CPU is idle during these waits.

2. CPU-Bound Tasks

Heavy calculations:

  • Image processing

  • Scientific computing

  • Encryption

  • Large data operations

Here, the CPU is busy the entire time.


Synchronous vs Asynchronous

Synchronous

Tasks happen one after another.

Asynchronous

Tasks can overlap and operate independently.

If one slow task blocks everything, performance suffers.

Concurrency allows tasks to run independently so slow tasks don’t block others.

If you want to see a practical example of asynchronous behavior in action, take a look at my detailed explanation of
https://w7gc.blogspot.com/2026/01/a-complete-guide-to-javascript-timers.html
That article breaks down how delayed execution works in the browser and how tasks can run without freezing the main thread — a concept closely connected to concurrency principles in Python.


What is a Queue?

A queue follows FIFO (First In, First Out).

Think of washing dishes:

  • One person washes.

  • One dries.

  • One puts away.

If washing is faster than drying, dishes pile up.

Queues help manage this workflow.

In Python (single machine):

from multiprocessing import Queue

Queues are used in:

  • Task management

  • Distributed systems

  • Worker pools

  • Message passing


Threads in Python

A thread runs inside a process.

Unlike processes:

  • Threads share memory.

  • Threads share global variables.

  • Threads are lightweight.

Example:

import threading def task(): print("Thread running") t = threading.Thread(target=task) t.start()

Important Differences

MultiprocessingThreading
Separate memoryShared memory
Safer isolationRisk of race conditions
Has terminate()No safe terminate()

Threads can be dangerous if:

  • They modify shared data

  • No synchronization is used


Thread Safety and Locks

When multiple threads modify shared data, problems happen.

To prevent this, use locks:

import threading lock = threading.Lock() def safe_task(): with lock: # modify shared variable safely pass

When to Use Threads vs Processes

Use threads for:

  • I/O-bound problems

  • Web requests

  • File operations

  • Waiting tasks

Use processes for:

  • CPU-heavy calculations

  • Parallel computation

  • Image processing

  • Mathematical workloads


concurrent.futures: The Modern Way

Python introduced concurrent.futures to simplify concurrency.

Instead of managing threads or processes manually, use pools.

Example:

import concurrent.futures import math import time def calc(x): time.sleep(1) return math.sqrt(x) values = [4, 16, 25, 36, 49] with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: results = executor.map(calc, values) for r in results: print(r)

You can switch to processes:

with concurrent.futures.ProcessPoolExecutor(max_workers=3) as executor:

What Happens with Different Worker Counts?

If:

  • 1 worker → tasks run serially

  • 5 workers (for 5 tasks) → ~1 second total

  • 3 workers → tasks finish in batches

This shows real concurrency behavior.


Getting Results As They Finish

Instead of waiting for all tasks:

with concurrent.futures.ThreadPoolExecutor() as executor: futures = [executor.submit(calc, v) for v in values] for future in concurrent.futures.as_completed(futures): print(future.result())

Now results appear as they complete — not in order.


Real-World Use Cases

Concurrency is useful for:

  • Web crawling

  • API requests

  • Resizing images

  • Processing large file sets

  • Running background services

  • Distributed task queues

Modern applications rely heavily on concurrency.


Why Concurrency Is Hard

Concurrency introduces complexity:

  • Race conditions

  • Deadlocks

  • Resource contention

  • Hard-to-debug bugs

The more workers you add, the more coordination you need.

Shared state becomes the biggest problem.

That’s why queues and task isolation are important.


              GOOD LUCK BUDDY (:

Comments

Popular posts from this blog

What I Learned About Linux Server Deployment (The Things No One Explains Clearly)

Understanding HTML Links, Structure, and Layout

How Python Really Handles Strings, Unicode, and Data