Multi-threading in Python

multi-threadingIn this blog post we will investigate how to implement concurrent processing in a Python program to allow multiple processes to be executed concurrently.

To do so will create and run multiple threads in our program and will need to use Python 3 and the threading library.

So what’s a thread and what is multi-threading?
In Python, a thread is a sperate process / flow of execution. Running multiple threads in a program allows multiple tasks to progress concurrently.

Let’s investigate one application of multi-threading using a basic computer program used to find very large prime numbers.

Prime Number Finder

In this example, we will create a class called PrimeNumberThread that derives from the Thread class of the threading library.

This class/thread will be used to find very large prime numbers from any given starting position (e.g. Checking any number greater than 100,000,000,000,000 one by one to see if they are a prime number or not).

We will then run three threads concurrently, each thread starting with a different starting position .e.g.

  • Thread 1 will look up for prime numbers, starting from number 100,000,000,000,000
  • Thread 2 will look up for prime numbers, starting from number 300,000,000,000,000
  • Thread 3 will look up for prime numbers, starting from number 500,000,000,000,000

As soon as a thread finds a prime number, it will display it on screen. All three threads will be working concurrently. You can run the following code to see the output generated by all three threads…

The above program is a very brief introduction to what is meant by running multiple threads in a computer program. There are a lot more concepts linked to multi-threading and you can find out more about these concepts by reading through this tutorial on multi-threading with Python.

Did you like this challenge?

Click on a star to rate it!

Average rating 4.4 / 5. Vote count: 31

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!