Python Threads v Processes
Threading is another concept that was covering in Chapter 1 of the Violent Python book. Threading is a form of parallelism that mean that code execution can run concurrently. A ‘process’ is also used to describe concurrent program execution, how a ‘thread’ and a ‘process’ are different. According to SO, processes are used for more heavyweight pieces of code execution. Threads run in a shared memory space, whereas processes run in a seperate memory space.
Furthermore, Python operates the Global Interpreter Lock (GIL). This is a controversial feature of Python that means it cannot take full advantage of the multiprocessing capabilites of the system it is running on. The article explains that each thread must have access to the GIL when interacting with Python objects.
Get Will Jones’s stories in your inbox
Join Medium for free to get updates from this writer.
Since threads are operating in the same memory space, this can mean that the state of a program can be incorrectly modified. For example, if two threads are incrementing the same memory location simultaneously, then the value might only increment by one instead of the correct amount, two.
This is a problem because it means that even in a multi-threaded application, only one thread is able to be executed at one time. If a thread is undergoing some blocking operation (i.e. an operation that is awaiting the completion of seperate operation), like file IO, the thread gives up the GIL so that another thread can use it. When the blocking operation has finished, the thread tries to reaquire the GIL so that it can continue.
To achieve true parallel programming, it is better to use the multiproccess module directly, in which each process it using it’s own memory space. However, this is limited by the number of processor / cores on your machine.








