Python Threading Basics
What is a Thread?
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. Thread in a computer program is an execution path. Threading is creating additional independent execution paths in your program. Every program starts with at least one execution path/thread. You can create more threads to execute parallel tasks depending on your requirements. It is a concept of efficient resource utilization . Having multiple threads in an application provides two very important potential advantages:- Improve an application's perceived responsiveness.
- Improve an application's real-time performance on multicore systems.
There are libraries to achieve it. It is important to note that Threading requires careful synchronization to avoid race conditions.
How to create a Thread in Python
The "thread" module provides simple functionalities and higher level interface is provided within the threading module that should be used instead. First thing you need to do is to import Thread using the following code:
from threading import Thread
A simple Thread program
The following example shows how to run a function as Threads in Python. The simplest way is via the thread module and its start_new_thread() method.
def yourFunc():
print "Funcion called!!"
thread.start_new_thread(yourFunc, ())
The thread.start_new_thread start a new thread and return its identifier. When the function returns, the thread silently exits.
example
import time
from threading import Thread
def myfunc(i):
print ("Before Sleep :", i)
time.sleep(5)
print ("After Sleep :", i)
for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()
Creating a Thread Class
Python provides the threading module which implements a layer on top of the thread module . The threading module provides, among other things, a Thread class which contains a run() method . Typical usage is to subclass the Thread class and override the run() method in the subclass to implement the desired functionality. In order to create a thread in Python you'll want to make your class work as a thread. For this, you should subclass your class from the Thread class .
class MyThreadClass(threading.Thread):
def run(self):
Here, MyThreadClass is a child class of the Thread class . Next step is to define a run method in this class. The run() method in the MyThreadClass is the entry point for a thread. The run() method will be executed when we call the start method of any object in our MyThreadClass class. You can write code inside the run() method for running thread activity. It is possible to pass a function or other callable object to the Thread class constructor to specify the target that the run() method will call. To do this, we can use the function thread.start_new_thread :
t = MyThreadClass()
t.start()
Full Source
import threading
import datetime
class MyThreadClass(threading.Thread):
def run(self):
dt = datetime.datetime.now()
print (self.getName(), " Current Date and Time : ", dt)
for i in range(5):
t = MyThreadClass()
t.start()
output
Thread-1 Current Date and Time : 2015-10-04 17:09:48.423745
Thread-2 Current Date and Time : 2015-10-04 17:09:48.423745
Thread-3 Current Date and Time : 2015-10-04 17:09:48.423745
Thread-4 Current Date and Time : 2015-10-04 17:09:48.423745
Thread-5 Current Date and Time : 2015-10-04 17:09:48.423745
In the above example, you can see the class ThreadClass inherits from threading.Thread and because of this, you need to define a run() method that executes the code you run inside of the thread. The only thing of importance to note in the run method is that self.getName() is a method that will identify the name of the thread. Finally, t.start() is what actually starts the threads.
Related Topics
- How to use Date and Time in Python
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Python filter() Function
- Difference between range() and xrange() in Python
- How to print without newline in Python?
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- Create a nested directory without exception | Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- How to Find the Mode in a List Using Python
- Difference Between Static and Class Methods in Python?