Threading in Python

It’s been observed that most of the students find it difficult to understand the concept of threading, but today with the help of this tutorial will try to make it clear.

So, threading is actually doing multiple things in one program or application then our system creates different threads for different operations. Suppose take an example of working in a text editor then it is doing multiple things like spell checking, saving, etc, hence CPU will create different threads for each of them. Threads run in the same memory space. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. Hope this makes sense so far.

In threading, operations/functions are executing parallel not simultaneously. We will take a look at it with a programming perspective as well. In Python, we have threading module in order to make our program working as a multiprocessing system/program. I will also tell you the difference between multiprocessing and multithreading.

Due to multicores available in systems, it helps in doing this multithreading. If you want to check the cores of your system. Just go like this -:
Task Manager -> Performance tab -> Check the cores info, currently running threads, etc.
There is a concept of lock-in threads as well. In threads as I mentioned that they execute in the same memory space. So, if two threads are executing the same variable then it might happen that one thread is updating the variable value and another thread is about to use that variable then there another thread might take some wrong value, here comes the concept of locking. In locking, what will do is will lock that variable until the modification has been completed. Now, let’s take a look at an example -:

Here, this is how threading is working. The output is machine dependent as well may be the order of hello and hi will not be the same as of mine. Hope you understood it clearly.

Difference between Multiprocessing and multithreading

The threading module uses threads and the multiprocessing uses processes. The difference is that threads run in the same memory space, while processes have separate memory. This is the reason sharing of objects in multiprocessing is quite difficult. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. For multiprocessing, you can refer -:

Stay tuned! Keep learning with us.


Close Menu