Tutorial by Examples

Python multithreading performance can often suffer due to the Global Interpreter Lock. In short, even though you can have multiple threads in a Python program, only one bytecode instruction can execute in parallel at any one time, regardless of the number of CPUs. As such, multithreading in cases w...
Use threading.Thread to run a function in another thread. import threading import os def process(): print("Pid is %s, thread id is %s" % (os.getpid(), threading.current_thread().name)) threads = [threading.Thread(target=process) for _ in range(4)] for t in threads: t.sta...
Use multiprocessing.Process to run a function in another process. The interface is similar to threading.Thread: import multiprocessing import os def process(): print("Pid is %s" % (os.getpid(),)) processes = [multiprocessing.Process(target=process) for _ in range(4)] for p in...
As all threads are running in the same process, all threads have access to the same data. However, concurrent access to shared data should be protected with a lock to avoid synchronization issues. import threading obj = {} obj_lock = threading.Lock() def objify(key, val): print("O...
Code running in different processes do not, by default, share the same data. However, the multiprocessing module contains primitives to help share values across multiple processes. import multiprocessing plain_num = 0 shared_num = multiprocessing.Value('d', 0) lock = multiprocessing.Lock() ...

Page 1 of 1