Python Tutorial - Learn Python From Scratch! + Multithreading




Hi everyone,

In this tutorial, I am going to give you necessary information to be able to begin Python Programming along with an advanced topic called Multithreading. But before we start, let me ask you a couple of questions:


What is Python?

Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.

Also, Python Software Foundation provides an online Python Interpreter so that everyone can write python code without even installing any IDEs.

Why is Python popular?

Because, Python is powerful and fast; plays well with others; runs everywhere; is friendly and easy to learn; is Open.

How easy is it?

Python can be very easy to pick up whether you're a first time programmer or you're experienced with other languages.

Alright, since we now know why we are learning Python, we can start. The following video tutorial by Derek Banas teaches the basics of Python Programming in 43 minutes! I strongly recommend you to watch this tutorial if you do not have any prior experience in Python. Then we are going to dive deeper and talk about multithreading in Python.


Here is the download link for the IDE (PyCharm): https://www.jetbrains.com/pycharm/download/


Hopefully, the video was helpful to understand the basics of the Python language. If you think that it was not enough to get familiar with the language, check out the following written tutorials on Python:

The next important topic after learning the basics is Multithreading.

Multithreading is similar to running multiple different programs concurrently, but with the following advantages:

  • Multiple threads within a process share the same memory space with the main thread and can therefore share information much more easily than if they were separate processes.
  • Threads are usually called light-weight processes and they do not require much memory overhead; they are cheaper than processes.

What is a Thread?

In software programming, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.

A thread has a starting point, an execution sequence, and a result. It has an instruction pointer that keeps track of the current state of the thread and it controls the next state.

How do we create a Thread?

In Python, there are 2 different ways to create a thread:

1- Calling the _thread method available in thread module,

2- Using the latest threading module.

The thread module has been "deprecated" for quite a long time. Users are encouraged to use the threading module instead. Therefore, the module "thread" is not available in Python 3. It has been renamed to "_thread" for backwards compatibilities in Python 3.

Now let's look at these two methods and give some examples using them:

1- Using the _thread Module


If you prefer the <_thread> module to apply in your program, then use the following method to start threads. 

_thread.start_new_thread ( function, args[, kwargs] )

This method call enables a fast and efficient way to create new threads. It returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread is terminated. Args represents the input arguments and kwargs is an optional dictionary of keyword arguments.
Following example shows how to use threads using _thread method:

import _thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# Create two threads as follows
try:
   _thread.start_new_thread( print_time, ("Thread-1", 1, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print("Error: unable to start thread")

while 1:
   pass


when we run this code, we obtain the following result:

Thread-1: Tue Sep  6 13:13:45 2016
Thread-1: Tue Sep  6 13:13:46 2016
Thread-1: Tue Sep  6 13:13:47 2016
Thread-2: Tue Sep  6 13:13:48 2016
Thread-1: Tue Sep  6 13:13:48 2016
Thread-1: Tue Sep  6 13:13:49 2016
Thread-2: Tue Sep  6 13:13:52 2016
Thread-2: Tue Sep  6 13:13:56 2016
Thread-2: Tue Sep  6 13:14:00 2016
Thread-2: Tue Sep  6 13:14:04 2016


_thread module is very effective for low-level threading, but it is very limited compared to the newer threading module.

 2 - Using the threading module 


The threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed previously.

The threading module contains all the methods of the thread module and provides these additional methods:

threading.activeCount(): Returns the number of thread objects that are active. threading.currentThread(): Returns the number of thread objects in the caller's thread control.
threading.enumerate(): Returns a list of all thread objects that are currently active. In addition to the methods, the threading module has the Thread class that implements threading.

The methods provided by the Thread class are as follows: 

 run(): The run() method is the entry point for a thread.
 start(): The start() method starts a thread by calling the run method.
 join([time]): The join() waits for threads to terminate.
 isAlive(): The isAlive() method checks whether a thread is still executing.
 getName(): The getName() method returns the name of a thread.
 setName(): The setName() method sets the name of a thread.

Use the following method to start threads with threading module. 
  • Construct a subclass from the <Thread> class.
  • Override the <__init__(self [,args])> method to supply arguments as per requirements.
  • Next, override the <run(self [,args])> method to code the business logic of the thread.
Once the new <Thread> subclass is defined, you have to instantiate it to start a new thread. Then, invoke the <start()> method to initiate it. It will eventually call the <run()> method to execute.


#!/usr/bin/python3

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("Starting " + self.name)
        print_time(self.name, self.counter, 5)
        print ("Exiting " + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")


Here is the result of the code above:

Starting Thread-1
Starting Thread-2
Thread-1: Tue Sep  6 13:39:38 2016
Thread-2: Tue Sep  6 13:39:39 2016
Thread-1: Tue Sep  6 13:39:39 2016
Thread-1: Tue Sep  6 13:39:40 2016
Thread-2: Tue Sep  6 13:39:41 2016
Thread-1: Tue Sep  6 13:39:41 2016
Thread-1: Tue Sep  6 13:39:42 2016
Exiting Thread-1
Thread-2: Tue Sep  6 13:39:43 2016
Thread-2: Tue Sep  6 13:39:45 2016
Thread-2: Tue Sep  6 13:39:47 2016
Exiting Thread-2
Exiting Main Thread

So far, we have covered the 2 different ways to use multithreading in Python. Since multithreading is a very wide concept, we are going to end this tutorial by giving you some valuable sources on this topic:


Hope you found this tutorial helpful. Please leave a comment if you have any questions or suggestions and don't forget to share :) Happy coding!

For more information on Multithreading in Python, please refer to the documentation
Author:

Software Developer, Codemio Admin

Disqus Comments Loading..