# Introduction to multithreading in Python

> An introduction to multithreading in Python: using the threading module and Thread() to run a slow function on its own thread while your program continues.

Author: Flavio Copes | Published: 2021-02-25 | Canonical: https://flaviocopes.com/python-multithreading/

A [Python](https://flaviocopes.com/python-introduction/) application runs on a single thread, unless you explicitly enable multithreading.

Why is multithreading useful? Code in Python is ran in sequence, one instruction after another.

If you define a function that sleeps 3 seconds and then prints something, like this:

```python
import time

def greet():
    time.sleep(3)
    print('hello')

greet()
print('world')
```

The `world` string is printed after 3 seconds, because we call `time.sleep(3)` inside the `greet()` function.

This is just a silly example, but imagine processing an image, getting a resource from the network, or writing a big file to disk. Anything that can take a lot of time.

With multithreading we can run the function that takes a lot of time into a separate thread, and go on with our program in the meantime.

The `threading` standard library module helps with implementing multithreading. You import `Thread` from it:

```python
from threading import Thread
```

Then we pass the function we must execute as the `target` argument to the `Thread()` function, getting a thread object:

```python
t = Thread(target=greet)
```

then we call its start() method to start the thread:

```python
t.start()
```

Try running this code:

```python
from threading import Thread
import time

def greet():
    time.sleep(3)
    print('hello')

t = Thread(target=greet)
t.start()

print('world')
```

You will now see `world` printed 3 seconds before `hello` shows up in the console.

The program does not end until the thread (or all the threads it started) end, unless you start a thread as a _deamon_.

Those are the basics of multithreading. This is complex, and can lead to the introduction of bugs if not done well.
