Manager
- Python course
- Expert
- Lesson 29/47
- 5 min
Learn shared state with multiprocessing.Manager.
What is multiprocessing.Manager?
multiprocessing.Manager creates Python objects shared between processes. It starts a server process; client processes access objects through a proxy.
Manager().list() gives a shared list and Manager().dict() a shared dict. Every operation on these objects is forwarded to the server process and made thread-safe. Unlike a plain list, a shared list can be safely modified by multiple processes. This is handy for complex shared state; but it is slower than direct communication.
Using a shared list
A Manager list is used like a plain list. .append(), [i] and len() work; but every operation goes to the server process.
Important: print(shared) prints the proxy; to see the real list use list(shared). A with Manager() as m: block automatically closes the server at the end. This prevents resource leaks. Shared objects are powerful; but remember every access has a cost.
Practice Shared list with Manager
Import with from multiprocessing import Manager. Open a with Manager() as m: block. Inside create a shared list with shared = m.list(). Append values with shared.append("a") and shared.append("b"). Print list(shared).
Starter code
# create a shared list with Manager
# append values and printSample solution
from multiprocessing import Manager
with Manager() as m:
shared = m.list()
shared.append("a")
shared.append("b")
print(list(shared))Expected output
['a', 'b']
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match Manager concepts
| Term | Meaning |
|---|---|
Manager |
Shared object server |
m.list() |
Shared list |
m.dict() |
Shared dict |
proxy |
Proxy access |
2 What does Manager().list() provide?
from multiprocessing import Manager
m = Manager()
shared = m.list()- A process object
- A plain Python list
- A list shared between processes Correct answer
- A queue
Explanation: Manager().list() returns a list safe to share between processes.
3 Complete the Manager call
from multiprocessing import ____
m = Manager()
from multiprocessing import Manager
m = Manager()
Explanation: Manager provides shared objects.