> For the complete documentation index, see [llms.txt](https://0xa1mn.gitbook.io/cyber-explained/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xa1mn.gitbook.io/cyber-explained/programming/python/system-pogramming/multithreading.md). Agents can also search and read this documentation through its [MCP server](https://0xa1mn.gitbook.io/cyber-explained/~gitbook/mcp).

# Multithreading

**Multithreading** is defined as the ability of a processor to execute multiple threads concurrently.

> In a simple, single-core CPU, it is achieved using frequent switching between threads. This is termed as **context switching**. In context switching, the state of a thread is saved and state of another thread is loaded whenever any interrupt (due to I/O or manually set) takes place. Context switching takes place so frequently that all the threads appear to be running parallelly (this is termed as **multitasking**).

```
import threading

def print_cube(num):
	"""
	function to print cube of given num
	"""
	print("Cube: {}".format(num * num * num))

def print_square(num):
	"""
	function to print square of given num
	"""
	print("Square: {}".format(num * num))

if __name__ == "__main__":
	# creating thread
	t1 = threading.Thread(target=print_square, args=(10,))
	t2 = threading.Thread(target=print_cube, args=(10,))

	# starting thread 1
	t1.start()
	# starting thread 2
	t2.start()

	# wait until thread 1 is completely executed
	t1.join()
	# wait until thread 2 is completely executed
	t2.join()

	# both threads completely executed
	print("Done!")

```

There is another way to execute threading  [check manual](https://docs.python.org/3/library/concurrent.futures.html)&#x20;
