DEV Community

Multithreading vs Multiprocessing in Python 🐍

Bosco Noronha on December 03, 2017

tldr; The Python threading module uses threads instead of processes. Threads uniquely run in the same unique memory heap. Whereas Processes run in...
Collapse
 
linehammer profile image
linehammer

The threading module uses threads, the multiprocessing module uses processes. The difference is that threads run in the same memory space, while processes have separate memory. This makes it a bit harder to share objects between processes with multiprocessing. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. This is what the global interpreter lock is for. Spawning processes is a bit slower than spawning threads. Once they are running, there is not much difference. More...net-informations.com/python/iq/mul...

Collapse
 
plaintextnerds profile image
Tim Armstrong

You've got a bug in your code for both the threading and processing examples: You're passing "number" as an arg to calc_quad but calc_quad accepts no args. As a result "number" is undefined in the function.

Collapse
 
jacopobonta profile image
Jacopo

In an attempt to see the differences between processes and threads I tried to add the result variable also to the first example. Since with thread we share the same memory heap i was expected to see print(result) outputting the square result. Instead like the example with the multiprocesses None was printed, can you or someone else explain me why this happens?

Collapse
 
mdah profile image
m-dah

Declare the "result" variable as global in main and threads so it does not create a new local variable for each thread.

Collapse
 
nnkteja profile image
N N K Teja

πŸ‘
u may have to pass number to
calc_quad(): => calc_quad(number):

also print('Quad': => print('Quad:'