Multithreading in Python
Multithreading in Python
in Python
Threads
– Threads are lightweight processes (subparts of a large process) that can run
concurrently in parallel to each other, where each thread can perform some
task.
– Threads are usually contained in processes. More than one thread can exist
within the same process. Within the same process, threads share memory and
the state of the process.
What is Multithreading?
– Modern computers have a CPU that has multiple processing cores and each of
these cores can run many threads simultaneously which gives us the ability to
perform several tasks concurrently. This process of running multiple Threads
concurrently to perform tasks in parallel is called Multithreading.
– Multithreading provides the following benefits:
– Multiple threads within a process share the same data space and can, therefore,
share information or communicate with each other more easily than if they were
separate processes.
– Threads do not require much memory overhead; they are cheaper than
processes in terms of memory requirements.
– Multithreaded programs can run faster on computer systems with multiple
CPUs because these threads can be executed concurrently.
Example
– Let's say you create a simple application for an Event's registration where
attendees must register if they wish to attend the event. You have a simple
HTML form for the users to fill in, and a backend which is a single threaded
application.
– As the application is single threaded, it can only process one request at a time.
But what if the event is a "Coldplay's Music Concert" where millions of people
want to register. Processing one request at a time will drastically slow down the
performance.
– So, we make the application multi-threaded and start multiple threads inside it
hence allowing parallel processing.
Multithreading in Python