DEV Community

petercour
petercour

Posted on

Threads with Python

A Thread is the smallest unit that can be scheduled in an operating system. In practice, threading is used when multiple things need to happen "at the same time".

For instance, while you click "download" in your web browser, you should be able to continue surfing the web while its download. It needs to happen "at the same time".

In reality computers use a scheduler, that give a tiny amount of time to each thread.

Python Threads

Can you use threads with Python? Yes, please!
To create a thread in Python

#!/usr/bin/python3
# threading example, https://pythonbasics.org/
import threading

# function that prints hello world and current thread
def task():
    print("Hello World: {}".format(threading.current_thread()))

# create a thread and start it
thread1 = threading.Thread(target=task)
thread1.start()

Because the thread finishes immediately, it only shows "Hello world". You can put a loop in a thread, to create "parallel running processes".

#!/usr/bin/python3
# threading example, https://pythonbasics.org/

import threading
import time

# function that prints hello world and current thread
def task():
    for i in range(0,10):
        print(" thread " + format(threading.current_thread()), end=''),
        print(" = " + str(i))
        time.sleep(1)

# create a thread and start it
thread1 = threading.Thread(target=task)
thread1.start()

# create a thread and start it
thread2 = threading.Thread(target=task)
thread2.start()

This then runs thread1 and thread2 at seemingly the same time. Both threads only count upwards.

thread <Thread(Thread-1, started 140453722031872)> = 0
thread <Thread(Thread-2, started 140453713639168)> = 0
thread <Thread(Thread-1, started 140453722031872)> = 1
thread <Thread(Thread-2, started 140453713639168)> = 1
thread <Thread(Thread-1, started 140453722031872)> = 2
thread <Thread(Thread-2, started 140453713639168)> = 2
...

Threads can be waiting for each other and block indefinitely. That is named a dead lock

Learn Python:

Top comments (0)