Python: threading and threads - how it works
Related Videos: Python Threading Tutorial: Run Code Concurrently Using the Threading Module (May 2024).
Threads allow you to run multiple processes in Python at the same time. We show you how this works in this practical tip.
Creating threads in Python - step by step
To run different processes in Python in parallel, you can create your own threads.
- First import the threading module and the sleep method with " import threading " and " from time import sleep ".
- First, define a method that you want to run in a thread. The sleep command, which stops the function at one point for a short time, is helpful for testing. In our example we define a method with: » def test (a): « ⮐ » print (" thread activated. ", A) « ⮐ » sleep (2) « ⮐ » print (" thread deactivated. ", A) «,
- In the next step we create a list of string values, the elements of which are to be transferred to the function afterwards: » list = [" 1 ", " 2 ", " 3 "] «.
- Now a for loop should iterate through the list and start the threads one after the other. We start with » for e in list: «.
- Next, the thread is initiated with " t = threading.Thread (target = test, args = (e, )) ". The "target" argument specifies the target method that the thread should execute. Parameters for this method can be passed at "args".
- Then you can set with " t.daemon = True " that the main program may be terminated, even if threads are still running in the background.
- The thread can finally be started with " t.start () ". We pause the for loop with " sleep (0.5) " for half a second. If you run this program now, you will see that the threads start in the background and the for loop does not wait for them to finish. This allows you to easily run processes in parallel.