From point A to point B
Point A: your scripts talk to one network device after another. If each connection takes half a second, checking 200 switches costs you almost 2 minutes of waiting. Point B: by the end of this chapter, you'll launch several tasks at once with threads and protect the data they share. You'll also connect to many devices in parallel with a thread pool.
Every example simulates network latency with time.sleep. That way you can run them without a lab and later swap the simulation for your real connection.
- Processes and threads: what they are and how they differ
- The GIL and where it really stands in Python 3.14
- Creating threads with
threading.Thread - Locks:
LockandRLock - Semaphores to limit simultaneous connections
- Conditions, events and a “synchronized” decorator
- Per-thread data with
threading.local - Sharing information with
queue.Queue - Thread pools with
ThreadPoolExecutor
Processes and threads
A process is a running program. Your computer seems to do many things at once: it plays music, syncs files and runs your script. With a single core, the processes actually take turns so fast that you perceive them as simultaneous.
Each turn requires a context switch. The operating system saves the state of the outgoing process in memory and loads the state of the incoming one. That work costs time and resources.
A thread (thread of execution, or lightweight process) is also running code, but it lives inside a process. Threads in the same process share its memory. That's why the system creates and switches them with less effort, and any global variable is visible to all of them.
That shared memory is both an advantage and a risk. Sharing data costs nothing, but 2 threads modifying the same data at the same time can leave it inconsistent. Much of this chapter is about how to avoid that.
os.fork or with the popen2 module. In Python 3, popen2 no longer exists: to launch external programs you use subprocess, and to spread Python work across processes, multiprocessing or concurrent.futures.ProcessPoolExecutor. os.fork is still available, but only on Unix-like systems.The GIL and where it stands in Python 3.14
The usual Python implementation, CPython, has a GIL (Global Interpreter Lock). It's a global lock that lets only one thread run Python bytecode at a time, even if the machine has 16 cores. It simplifies the interpreter and C extensions, but it limits real parallelism.
The interpreter switches between threads every so often, about 5 milliseconds by default. It also releases the GIL when a thread sleeps with time.sleep or waits on an input/output operation: reading a file, waiting for a router's reply, downloading a page.
That leads to the rule of thumb that will serve you best in network automation:
- Tasks that wait (SSH, REST APIs, SNMP, disk reads): threads work very well, because while one waits, another moves forward.
- Tasks that compute (processing millions of lines, encrypting, compressing): with the GIL, threads don't speed things up. There you're better off with processes.
Python 3.14 offers a special free-threaded build (without the GIL). PEP 779 made it officially supported in 3.14, but it's still optional: the default build keeps the GIL. You can check which one you're using:
import sys
import sysconfig
print(sys.version_info[:2])
print("Free-threaded build:", sysconfig.get_config_var("Py_GIL_DISABLED") == 1)
print("GIL enabled now:", sys._is_gil_enabled())
print("Switch interval:", sys.getswitchinterval(), "s")
$ python3 gil.py
(3, 14)
Free-threaded build: False
GIL enabled now: True
Switch interval: 0.005 s
If your interpreter shows False on the second line, you have the regular build, with the GIL. Python 3.14 also adds the concurrent.interpreters module (PEP 734) and concurrent.futures.InterpreterPoolExecutor, which run code in several isolated interpreters within the same process. They're advanced tools; for now it's enough to know they exist.
sys.setcheckinterval. That function no longer exists: today switching is time-based, and you read or set it with sys.getswitchinterval() and sys.setswitchinterval(). For the same reason, the advice to run with -O to reduce context switches no longer applies. The processing module the book mentioned became multiprocessing, part of the standard library.Creating threads with threading.Thread
The threading module offers an object-oriented API for working with threads. The central piece is the Thread class. There are 2 ways to use it.
Way 1: inherit from Thread. You write the thread's work in the run method. If you define your own __init__, call super().__init__() first so the object is properly initialized.
import threading
import time
class Probe(threading.Thread):
def __init__(self, router):
super().__init__() # initialize the Thread part of the object
self.router = router
def run(self): # the code the thread runs
time.sleep(0.1) # simulate waiting on the network
print(f"{self.router} replies")
threads = [Probe(r) for r in ("r1", "r2", "r3")]
for thread in threads:
thread.start() # start run() in parallel
print("Main thread: probes launched")
for thread in threads:
thread.join() # wait for each one to finish
print("Main thread: all done")
start() sets the thread going and runs run concurrently with the main thread. join() blocks the caller until the thread finishes. It accepts a timeout in seconds so you don't wait forever.
$ python3 probe.py
Main thread: probes launched
r1 replies
r2 replies
r3 replies
Main thread: all done
Run it several times: the order of the replies may change. With threads you don't control who finishes first, and your code shouldn't depend on that order.
Way 2: pass a function. You create a Thread directly and tell it what to run with target, plus its arguments in args (a tuple) and kwargs (a dictionary). It's the most common way today, because it doesn't force you to create a class. You can also give it a name with name.
import threading
import time
def back_up(router, path):
time.sleep(0.1)
print(f"Backup of {router} saved to {path}")
threads = []
for router in ("r1", "r2"):
t = threading.Thread(
target=back_up,
args=(router,),
kwargs={"path": f"/backups/{router}.cfg"},
name=f"backup-{router}",
)
t.start()
threads.append(t)
print([t.name for t in threading.enumerate()])
print("Live threads:", threading.active_count())
for t in threads:
t.join(timeout=2) # wait 2 seconds at most
print(t.name, "still alive:", t.is_alive())
print(threading.current_thread() is threading.main_thread())
try:
threads[0].start() # a thread can only be started once
except RuntimeError as e:
print("RuntimeError:", e)
$ python3 backup.py
['MainThread', 'backup-r1', 'backup-r2']
Live threads: 3
Backup of r1 saved to /backups/r1.cfg
Backup of r2 saved to /backups/r2.cfg
backup-r1 still alive: False
backup-r2 still alive: False
True
RuntimeError: threads can only be started once
This example shows several inspection tools:
threading.enumerate()returns the live threads, including the main one.threading.active_count()counts how many there are.t.is_alive()tells you whether a thread is still running.threading.main_thread()returns the main thread, andthreading.current_thread()the thread running the current line.
Look at the last line of the output: calling start() twice raises a RuntimeError. A thread starts only once; if you need to repeat the work, create another thread.
A daemon thread is a service thread. When only daemon threads remain alive, the program ends without waiting for them. They're meant for background tasks, like a keepalive, that shouldn't stop the script from finishing. Keep in mind that they're cut off abruptly, without closing files or connections.
The Timer class is a thread that waits for a delay and then runs a function. Its cancel() method stops it if the delay hasn't expired yet.
import threading
import time
def keepalive():
while True: # infinite loop: never ends on its own
time.sleep(0.05)
threading.Thread(target=keepalive, daemon=True).start()
def alarm():
print("No reply from r1 in 0.2 s: opening a ticket")
timer = threading.Timer(0.2, alarm)
timer.start()
time.sleep(0.3)
other = threading.Timer(5, alarm)
other.start()
other.cancel() # cancelled before it expires
print("End of program; the daemon thread dies with it")
$ python3 timer.py
No reply from r1 in 0.2 s: opening a ticket
End of program; the daemon thread dies with it
thread module; in Python 3 it's called _thread, it's low-level, and you'd normally use threading. Since 3.7, thread support is always built in. The camelCase names changed. isAlive() was removed: use is_alive(). getName(), setName(), setDaemon(), activeCount() and notifyAll() have been deprecated since 3.10. Use the name and daemon attributes, active_count() and notify_all() instead. The verbose parameter is gone, and instead of Thread.__init__(self) you write super().__init__().Locks: Lock and RLock
Picture 4 threads adding packets to the same counter. The operation packets += 1 looks like one step, but it's several: read the value, add 1 and store it. If 2 threads read the same value before storing, an increment is lost. That delicate piece of code is called a critical section.
A lock (also called a mutex, from mutual exclusion) has 2 states: acquired or free. When a thread acquires it, any others that request it block until it's released. That way, only one thread at a time enters the critical section.
The methods are acquire() and release(), but the recommended way is with. The with block acquires the lock on entry and releases it on exit, even if an exception occurs. If you forget a release(), your program hangs forever.
import threading
packets = 0
lock = threading.Lock()
def count(n):
global packets
for _ in range(n):
with lock: # acquire and release even on exceptions
packets += 1
threads = [threading.Thread(target=count, args=(100_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Packets counted:", packets) # always 400000
# non-blocking acquire: returns True or False right away
print(lock.acquire(blocking=False)) # True: it was free
print(lock.acquire(blocking=False)) # False: already acquired
lock.release()
print(lock.acquire(timeout=0.1)) # True
lock.release()
$ python3 counter.py
Packets counted: 400000
True
False
True
acquire(blocking=False) doesn't wait: it returns True if it got the lock and False if it was taken. With acquire(timeout=0.1) you wait for that long at most. All the primitives you'll see next accept these same options.
A plain Lock has a trap: if the same thread tries to acquire it twice, it blocks itself. The RLock class (reentrant lock) allows it. The owner can acquire it several times, and it becomes free once released as many times as it was acquired. It's useful when a protected function calls another one that uses the same lock.
import threading
lock = threading.RLock()
inventory = {}
def add(host, ip):
with lock:
inventory[host] = ip
def add_batch(devices):
with lock: # first acquisition
for host, ip in devices:
add(host, ip) # second acquisition, same thread
add_batch([("r1", "10.0.0.1"), ("sw1", "10.0.0.11")])
print(inventory)
$ python3 inventory.py
{'r1': '10.0.0.1', 'sw1': '10.0.0.11'}
Semaphores to limit connections
A semaphore is a lock with a quota. Semaphore(n) lets up to n threads in at once; with no argument, the quota is 1. Each acquire() subtracts 1 from the counter, each release() adds 1, and only when the counter reaches 0 do the next threads wait.
In networking it's very practical. Many devices limit simultaneous SSH sessions, and an API may reject you if you send hundreds of requests together. A semaphore protects you without changing the rest of the code.
import threading
import time
sessions = threading.Semaphore(2) # at most 2 SSH sessions at once
active = 0
peak = 0
counter = threading.Lock()
def connect(host):
global active, peak
with sessions:
with counter:
active += 1
peak = max(peak, active)
time.sleep(0.1) # simulate work on the device
with counter:
active -= 1
threads = [threading.Thread(target=connect, args=(f"sw{i}",)) for i in range(6)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Peak simultaneous sessions:", peak)
bounded = threading.BoundedSemaphore(1)
bounded.acquire()
bounded.release()
try:
bounded.release() # one release too many
except ValueError as e:
print("ValueError:", e)
$ python3 sessions.py
Peak simultaneous sessions: 2
ValueError: Semaphore released too many times
An important detail: the initial value isn't a ceiling. If you call release() more times than you should, the counter goes above its original value. BoundedSemaphore prevents that and raises ValueError, as you see on the last line. Use it to catch logic errors.
Conditions, events and a synchronized decorator
A condition (Condition) lets a thread wait until something is true. It uses a lock internally: the one you pass it or, if you pass none, its own RLock. It fits the classic producer-consumer problem.
Here's how it works:
- The waiting thread acquires the condition (with
with) and callswait(). That releases the lock and puts it to sleep. - Another thread acquires the condition, changes the data and calls
notify()to wake one thread, ornotify_all()to wake them all. - The awakened thread gets the lock back and continues. Both release it when they leave the
with.
wait_for(predicate) is the safer version: it waits until the function returns a true value. That way, spurious wakeups and notifications that arrive too early don't affect you.
import threading
alerts = []
cond = threading.Condition()
def consumer():
with cond:
cond.wait_for(lambda: alerts) # wait until there are alerts
print("Processing:", alerts.pop(0))
def producer(message):
with cond:
alerts.append(message)
cond.notify() # wake one waiting thread
t = threading.Thread(target=consumer)
t.start()
producer("%LINK-3-UPDOWN: Gi0/1 down")
t.join()
$ python3 alerts.py
Processing: %LINK-3-UPDOWN: Gi0/1 down
An event (Event) is simpler: an internal flag that starts out false. Threads that call wait() block until another calls set(), and then they all wake up. There's no acquire or release: the lock stays hidden. clear() sets the flag back to false, and wait(timeout) returns False if the time ran out.
import threading
import time
window_open = threading.Event()
def apply_change(router):
print(f"{router}: waiting for the maintenance window")
window_open.wait() # blocks until set()
print(f"{router}: applying the change")
threads = [threading.Thread(target=apply_change, args=(r,)) for r in ("r1", "r2")]
for t in threads:
t.start()
time.sleep(0.2)
print("The window opens")
window_open.set() # wake everyone who's waiting
for t in threads:
t.join()
print(window_open.is_set())
window_open.clear()
print(window_open.wait(timeout=0.1)) # False: time ran out
$ python3 window.py
r1: waiting for the maintenance window
r2: waiting for the maintenance window
The window opens
r1: applying the change
r2: applying the change
True
False
If you come from Java, you may miss the synchronized keyword. In Python you can build a decorator that wraps any function with a lock. That's how you protect, for example, writes to a shared change log:
import functools
import threading
from pathlib import Path
def synchronized(lock):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with lock:
return func(*args, **kwargs)
return wrapper
return decorator
log_lock = threading.Lock()
Path("changes.log").unlink(missing_ok=True) # start with an empty log
@synchronized(log_lock)
def record(line):
with open("changes.log", "a", encoding="utf-8") as f:
f.write(line + "\n")
threads = [threading.Thread(target=record, args=(f"r{i}: config saved",))
for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
with open("changes.log", encoding="utf-8") as f:
print(len(f.readlines()), "complete lines")
print(record.__name__)
$ python3 change_log.py
5 complete lines
record
functools.wraps keeps the name and documentation of the original function, which is why the last line prints record and not wrapper.
Per-thread data
Sometimes you want a global variable, but with a different value in each thread. For example, the open session with the device each thread is handling. threading.local() creates a store whose attributes are independent per thread: what one thread saves, the others don't see.
import threading
session = threading.local()
def work(router):
session.device = router # each thread sees its own value
print(threading.current_thread().name, "->", session.device)
session.device = "main"
threads = [threading.Thread(target=work, args=(r,), name=f"t-{r}")
for r in ("r1", "r2")]
for t in threads:
t.start()
for t in threads:
t.join()
print("In the main thread it's still:", session.device)
def no_value():
try:
print(session.device)
except AttributeError as e:
print("AttributeError:", e)
t = threading.Thread(target=no_value)
t.start()
t.join()
$ python3 local_sessions.py
t-r1 -> r1
t-r2 -> r2
In the main thread it's still: main
AttributeError: '_thread._local' object has no attribute 'device'
The last thread never assigned session.device. Even though the main thread did, for that thread the attribute doesn't exist and an AttributeError comes up.
Sharing information with queue.Queue
Coordinating threads with locks takes practice, and mistakes are common. To pass data from one thread to another there's a better option: queue.Queue, a thread-safe FIFO queue (first in, first out). It takes care of the synchronization.
Queue(maxsize=n)limits the size; with 0 or no argument there's no limit.put(item)adds andget()removes. Both wait by default:getuntil there's something,putuntil there's room.block=Falseavoids waiting andtimeoutlimits it. If it can't proceed, it raisesqueue.Fullorqueue.Empty.qsize(),empty()andfull()report the state. Their answer is approximate while other threads are working.task_done()andjoin()let you wait until everything put in the queue has been processed.
This parser receives syslog lines through the queue and reports the ones with severity 3. The value None works as a sentinel: it tells the thread there's no more work.
import queue
import threading
q = queue.Queue(maxsize=100) # 0 or nothing: no limit
def parser():
while True:
line = q.get() # blocks until there's something
if line is None: # "sentinel": end signal
q.task_done()
break
if "-3-" in line: # severity 3 = error
print("ERROR:", line)
q.task_done()
t = threading.Thread(target=parser)
t.start()
syslog = [
"%SYS-5-CONFIG_I: Configured from console",
"%LINK-3-UPDOWN: Interface Gi0/2, changed state to down",
"%OSPF-5-ADJCHG: Nbr 10.0.0.2 from LOADING to FULL",
]
for line in syslog:
q.put(line)
q.put(None)
q.join() # wait until everything is processed
t.join()
print("Pending:", q.qsize(), "| empty:", q.empty(), "| full:", q.full())
$ python3 syslog_queue.py
ERROR: %LINK-3-UPDOWN: Interface Gi0/2, changed state to down
Pending: 0 | empty: True | full: False
import queue
q = queue.Queue(maxsize=1)
q.put("r1")
try:
q.put("r2", block=False) # it's full and we don't want to wait
except queue.Full:
print("queue.Full")
print(q.get())
try:
q.get(timeout=0.1) # empty: waits 0.1 s and gives up
except queue.Empty:
print("queue.Empty")
$ python3 queue_errors.py
queue.Full
r1
queue.Empty
Queue (capitalized), and you used it as Queue.Queue, Queue.Empty and Queue.Full. In Python 3 it's called queue. The book's example drained the queue with get(False) until it got Empty. With a sentinel and task_done(), the end is explicit and doesn't depend on when the thread checks the queue.Thread pools with ThreadPoolExecutor
Creating, starting and waiting for threads one by one works, but it gets repetitive. The concurrent.futures module offers ThreadPoolExecutor: a group of reusable threads you hand tasks to. It's the ideal tool for connecting to many network devices in parallel.
submit(function, argument) schedules a task and returns a future, an object that will hold the result when the task finishes. as_completed hands you the futures as they finish, and result() returns the value or re-raises the exception that happened inside the thread.
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
DEVICES = {"r1": "10.0.0.1", "r2": "10.0.0.2", "sw1": "10.0.0.11",
"sw2": "10.0.0.12", "fw1": "10.0.0.254"}
def get_version(host):
time.sleep(0.5) # simulate SSH or API latency
if host == "fw1":
raise TimeoutError(f"{DEVICES[host]} isn't responding")
return f"{host} ({DEVICES[host]}): IOS XE 17.9"
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(get_version, h): h for h in DEVICES}
for future in as_completed(futures):
host = futures[future]
try:
print(future.result())
except TimeoutError as e:
print(f"{host}: failed -> {e}")
print(f"Total time: {time.perf_counter() - start:.1f} s")
$ python3 parallel_inventory.py
r1 (10.0.0.1): IOS XE 17.9
r2 (10.0.0.2): IOS XE 17.9
sw1 (10.0.0.11): IOS XE 17.9
sw2 (10.0.0.12): IOS XE 17.9
fw1: failed -> 10.0.0.254 isn't responding
Total time: 0.5 s
There are 5 devices and each one takes half a second. In series that would be 2.5 seconds; in parallel, the time of the slowest one. Plus, the failure on fw1 doesn't stop the others: each error stays inside its future.
If order matters to you and you don't need to handle errors separately, map is more compact. It returns the results in the same order as the input:
import time
from concurrent.futures import ThreadPoolExecutor
def ping(ip):
time.sleep(0.2)
return ip, "ok"
ips = [f"10.0.0.{n}" for n in range(1, 6)]
with ThreadPoolExecutor(max_workers=5) as pool:
for ip, status in pool.map(ping, ips): # keeps the input order
print(ip, status)
$ python3 parallel_ping.py
10.0.0.1 ok
10.0.0.2 ok
10.0.0.3 ok
10.0.0.4 ok
10.0.0.5 ok
The with block waits for all the tasks to finish and releases the threads on exit. If you don't set max_workers, Python picks a value based on the available cores, up to a maximum of 32. For compute work, swap ThreadPoolExecutor for ProcessPoolExecutor: the interface is the same.
Challenge
Answer before you open the solution.
1. You need to query the API of 300 access points and each response takes 1 second. Threads or processes?
Threads. The task spends almost all its time waiting on the network, and the GIL is released during that wait. A ThreadPoolExecutor with a few dozen threads cuts the total time drastically. Processes pay off when the work is pure computation.
2. Why is with lock: better than acquire() and release()?
Because it always releases the lock. If an exception occurs between acquire and release, the lock stays taken and the other threads wait forever. The with block releases it on exit, no matter what.
3. A device allows 3 simultaneous SSH sessions. Which primitive would you use to respect that limit?
A semaphore: threading.BoundedSemaphore(3). It lets up to 3 threads in at once and makes the rest wait. The bounded version also warns you with ValueError if you release too many times.
4. What's the difference between Condition.notify() and Event.set()?
notify() wakes one thread; set() wakes them all. Also, with a condition you acquire and release the lock yourself, while the event hides it. The event stays set until you call clear().
5. Did Python 3.14 remove the GIL?
Not in the default build. There's a free-threaded build, officially supported since 3.14 (PEP 779), but it's optional. Check with sys._is_gil_enabled() or with sysconfig.get_config_var("Py_GIL_DISABLED").
Key takeaways
- Threads in a process share memory: sharing data is instant, but you need to synchronize access.
- With the GIL, threads speed up tasks that wait (network, disk); for heavy computation, use processes.
- Create threads with
threading.Thread(target=..., args=...), start them withstart()and wait for them withjoin(). Lock,RLock,Semaphore,ConditionandEventsolve different problems; always use them withwithwhen you can.queue.Queueis the safest way to pass data between threads.ThreadPoolExecutoris your everyday tool for talking to many network devices in parallel.
In the next chapter, you'll save Python objects to disk and send them over the network with serialization: pickle, shelve and JSON.
Official resources
- threading: thread-based parallelismdocs.python.org
- queue: a synchronized queue classdocs.python.org
- concurrent.futures: launching parallel tasksdocs.python.org
- Python support for free threadingdocs.python.org
- PEP 779: official support for the free-threaded buildpeps.python.org
- multiprocessing: process-based parallelismdocs.python.org
Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.