Threading in Python | What is Threading in Python?

Share on facebook
Share on twitter
Share on linkedin
Share on telegram
Share on whatsapp

Contents

Threading en Python: make your code smarter

Python is great and we know it. But, Can you get smart enough in processing aspects? Threading shows the way.

What is parallelism?

Older machines used to have a single core inside the CPU where all the processing used to take place.

Why is the number of cores important? It is because it indicates the ability of the machine to handle multiple things. If you have 16 cores, can do 16 different operations at the same time.

Suppose you want to perform 16 different addition operations and suppose that each operation takes 1 second. In a single core machine, you must perform these operations one by one, which means that 16 addition operations are performed in 16 seconds. Now, in a machine 16 cores, can implement the 16 add operations on each kernel at the same time and do the work in 1 second. Is named Parallelism.

enhenbrate

Hilo is a set of operations to be executed. The thread will be implemented in one of the CPU cores. Note: 1 thread can be implemented only in 1 core, cannot be transferred / change teeth

Let's unfold two threads in a core. Note: a core can only do one thing at a time.

1d5wqvcsyf4f74mgt2g_k_g-8327670

Now we can process the two threads in any way we want.

First, we can process half of the first thread.

1i_fogu8psxcsklkalrapxg-6670733

Half of the next thread can now be processed.

1myabkoktklk8zsv-z_ddyw-6315981

The remaining half of the threads can be similarly processed.

1ly2quxkj5r45r50aeipz0g-9476205

This is what threading is This is how we run different things on the same CPU core. TLDR- Threading is about how we handle threads in a kernel.

Note- Threading does not imply multi-core execution. This is how to sequence the set of programs (threads) in the very core. In the example above, we will tell the CPU how to sequence and execute the two threads on the given kernel.

In fact, you can see how many threads are currently running on your machine. In Windows: go to Task Manager → Performance → CPU.

Why do we need to thread? Why can't we process one thread at a time and move on to the next?

Sometimes, a thread can hang, which means it is supposed to be idle at the moment. the best example is the time.sleep function (), that does nothing but wait a certain time. While a thread is idle / hanged, we can go ahead and process the other thread until the previous thread is activated. TLDR: when a thread is waiting, can process the other thread in the meantime.

This is exactly what we call CCurrent computing.

A small example

Let's explain threading with a small example. Look at the code snippet below.

#Part One of the code
import time
print(1)
time.sleep(10)
print('Done sleeping)
print(2)

#Part Two of the code
print(3)

When you run all the code as a single thread, the code is executed step by step. First, the library is imported. Then '1' is printed. Threads sleep during 10 seconds. the following is printed “2” followed by “Ready to sleep” and finally the “3”.

Output-
1
Done sleeping
2
3

Now let's say you are running the code as two threads. The first part as thread and the second as thread. (Note: by default, Python code is not provided with threads; we need to import the get pregnant library to do so.)

First, the library is imported and then '1' is printed. Now the thread goes to sleep. This is where threading comes in.

1z6k2rdchniexyauc9mr4ha-8942500

The core now switches to the other thread.

1cy3uh65nbl8wnwwdihdmxq-7134652

Now '3' is printed. Since the whole process is done in the thread 2, the kernel now returns to the thread 1 (which is still in suspension).

1uxcednvax6f506e3ht-fpq-6985366

Now, after the duration of sleep, '2' is printed.

Then the output will be

Output-
1
3
Done sleeping
2

Practical example

As always, a concept is only clear when we explain it with a real world example. The processes of E / S are the ones that benefit from the thread.

Suppose you are watching Shawshank Redemption on Netflix. Now two things happen as you watch Andy Dufresne suffer in jail: a: the application gets data from the server, From: the data obtained is shown to you as a movie on the screen.

1g8rkyd8cytziwiazj0ka_q-5516699

Imagine what the situation would be without threading. I would have to wait for the video to download from time to time, see the segment that was obtained, wait for the next segment to download, etc.

Thanks to the thread, we can divide the two processes into different threads. While a thread gets data (namely, is in sleep mode / suspension), the other thread can show you the amazing performance of Morgan Freeman.

It is also very useful for you as a data scientist. For instance, when you extract data from multiple web pages, you can simply deploy them across multiple threads and make it faster. Even when you send the data to a server, you can do this on multiple threads, so that when a thread is idle, others can be activated.

A detailed example

As said before, by default, Python code is not provided with threads; we need to import the thread library to do so.

Take a look at the code.

import threading
import time

def sleepy_man(Secs):
    print('Starting to sleep inside')
    time.sleep(Secs)
    print('Woke up inside')

x = threading. Thread(target = sleepy_man, args = (1,))
x.start()
print(threading.activeCount())
time.sleep(1.2)
print('Done')

If you run the above code, you will get the following result.

Output-
Starting to sleep inside
2
Woke up inside
Done

First, let me explain the code step by step. Then we will analyze the output.

  • Import the library get pregnant Y weather. get pregnant is the library that will allow us to create threads and weather is the library that contains the sleep function.
  • The function sleepy_man take in an argument seconds. First print 'Starting to sleep inside'. Then sleep for the seconds seconds and then print 'I woke up inside'.
  • This is the part where we start creating threads. We need to define by calling the class thread. We need to pass two arguments: objective what is the block of functions that needs to be threaded, arguments what are the arguments that should be passed to the function. A thread object that is now stored in x is returned.
x = threading. Thread(target = sleepy_man, args = (10,))
  • Now, after you define the thread class, we need to call the function start() to start threading
  • Note- Now we have two threads. A default thread for the program and a
    new thread that we define. Therefore, the number of active threads is two.
  • Therefore, the declaration must print '2'.
print(threading.activeCount())

Now let's look at the control flow. Once you call start() method, shoot sleepy_man () and runs on a separate thread. The main program will also run in parallel as another thread. The flow is shown in the image below.

45642screenshot202021-04-2020at205-57-3920pm-9816829

Now let's increase the time in which the program sleeps within the function.

import threading
import time

def sleepy_man(Secs):
    print('Starting to sleep inside')
    time.sleep(Secs)
    print('Woke up inside')

x = threading. Thread(target = sleepy_man, args = (4,))
x.start()
print(threading.activeCount())
time.sleep(1.2)
print('Done')

The output is as follows:

Starting to sleep inside
2
Done
Woke up inside

The flow is given in the diagram below:

22165screenshot202021-04-2020at206-02-3120pm-3942363

Now let's spice things up a bit. Let's run a loop for that triggers multiple threads.

import threading
import time

def sleepy_man(Secs):
    print('Starting to sleep inside - Iteration {}'.format(5-Secs))
    time.sleep(Secs)
    print('Woke up inside - Iteration {}'.format(5-Secs))

for i in range(3):
    x = threading. Thread(target = sleepy_man, args = (5-i,))
    x.start()

print('Active threads- ', threading.activeCount())

In each iteration, we activate a thread. Note that we pass the arguments 5, 4, 3 a 1S t, 2North Dakota, Y 3rd iteration respectively. Therefore, the sleepy_man () sleep 5 seconds, 4 seconds and 3 seconds respectively.

Therefore, the output is as shown:

Starting to sleep inside - Iteration 0
Starting to sleep inside - Iteration 1
Starting to sleep inside - Iteration 2
Active threads-  4
Woke up inside - Iteration 2
Woke up inside - Iteration 1
Woke up inside - Iteration 0

Therefore, we have seen how multiple threads can be defined and activated, which guarantees a better way of processing, which is very essential for E operations / S heavy.

The media shown in this article is not the property of DataPeaker and is used at the author's discretion.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.