December 2018
Beginner to intermediate
796 pages
19h 54m
English
The threading module offers a way to implement local data for threads. Local data is an object that holds thread-specific data. Let me show you an example, and allow me to sneak in a Barrier too, so I can tell you how it works:
# local.pyimport threadingfrom random import randintlocal = threading.local()def run(local, barrier): local.my_value = randint(0, 10**2) t = threading.current_thread() print(f'Thread {t.name} has value {local.my_value}') barrier.wait() print(f'Thread {t.name} still has value {local.my_value}')count = 3barrier = threading.Barrier(count)threads = [ threading.Thread( target=run, name=f'T{name}', args=(local, barrier) ) for name in range(count)]for t in threads: t.start()
We start by defining local ...
Read now
Unlock full access