Skip to content

Commit 15b5690

Browse files
committed
Add subinterpreters.py lesson
1 parent 13aeb6a commit 15b5690

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Multi-interpreter support via concurrent.interpreters in Python 3.14 (PEP 734).
3+
4+
Python subinterpreters allow running Python code in truly isolated
5+
environments within a single process. In Python 3.14, each interpreter
6+
has its own Global Interpreter Lock (GIL), enabling true multi-core
7+
parallelism for Python code.
8+
"""
9+
import concurrent.futures
10+
import concurrent.interpreters as interpreters
11+
12+
13+
def run_worker(data):
14+
"""Function to be run in a subinterpreter."""
15+
# This code runs in a different interpreter environment
16+
return f"Processed {data} in a subinterpreter"
17+
18+
19+
def main():
20+
# 1. Create a subinterpreter
21+
# The 'interpreters' module provides a high-level API
22+
interp = interpreters.create()
23+
24+
assert isinstance(interp, interpreters.Interpreter)
25+
assert interp.is_running() is False
26+
27+
# 2. Run code in the subinterpreter
28+
# We can run simple strings of code
29+
interp.exec("1 + 1")
30+
31+
# 3. Using InterpreterPoolExecutor for easier management
32+
# This is similar to ThreadPoolExecutor or ProcessPoolExecutor
33+
with concurrent.futures.InterpreterPoolExecutor(max_workers=2) as executor:
34+
# Submit tasks to the pool
35+
future1 = executor.submit(run_worker, "Task A")
36+
future2 = executor.submit(run_worker, "Task B")
37+
38+
# Get results (this handles passing data back and forth)
39+
result1 = future1.result()
40+
result2 = future2.result()
41+
42+
assert result1 == "Processed Task A in a subinterpreter"
43+
assert result2 == "Processed Task B in a subinterpreter"
44+
45+
# 4. Cleaning up
46+
interp.close()
47+
assert interp.id not in [i.id for i in interpreters.list_all()]
48+
49+
50+
if __name__ == "__main__":
51+
main()

0 commit comments

Comments
 (0)