Lesson 47 of 55
10 mins readPython Concurrency, forkIO & MVars
In Plain English
GHC includes ultra-lightweight green threads scheduled across CPU cores. Spawn threads with forkIO and communicate safely using synchronized MVar memory cells.
Deep Dive: How It Works
Green Threads (forkIO): GHC threads take only ~1KB of memory, allowing millions of concurrent threads.
MVar: A synchronized mutable location that is either empty or full. takeMVar blocks until full; putMVar blocks until empty.
Software Transactional Memory (STM): Atomic, composable memory transactions using atomically and TVars.
Core Rules to Remember

Lightweight Threads (forkIO): Spawn tens of thousands of concurrent green threads with minimal overhead.

MVar Synchronization: Thread-safe lock-free communication primitive.
Live Interactive Example
Hit Run Code to see it liveMVar Synchronization Between Threads
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: takeMVar blocked until the worker thread populated the MVar.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Put and Take MVar in Sequence
Create an empty MVar, put `"Ready"`, and take it.
Print `"Status: "` followed by the extracted value.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.