MultiThreading In Python

What is Threading?

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 . In the previous chapter, you can study in detail about... Threading in Python

What is Multithreading ?

Multithreading is a core concept of software programming that almost all the high-level programming languages support. Multithreaded programs are similar to the single-threaded programs that you have been studying. They differ only in the fact that they support more than one concurrent thread of execution-that is, they are able to simultaneously execute multiple sequences of instructions. These threads share the process resources but are able to execute independently. That means that a single process can have many different "functions" executing concurrently, allowing the application to better use the available hardware (multiple cores/processors). For example, a multithreaded operating system may run several background tasks, such as logging file changes, indexing data, and managing windows at the same time.

Python Multithreaded Programming

The following example demonstrate how a multithreaded program execute in Python.

import time import threading class myThread(threading.Thread): def __init__(self, threadID): threading.Thread.__init__(self) self.threadID = threadID def run(self): for x in range(1, 5): print(" Thread ID :",self.threadID) time.sleep(1) print(" ") t1 = myThread(1) t1.start() t1 = myThread(2) t1.start() t1 = myThread(3) t1.start() t1 = myThread(4) t1.start()
Thread ID : 1 Thread ID : 2 Thread ID : 3 Thread ID : 4 Thread ID : 1 Thread ID : 4 Thread ID : 3 Thread ID : 2 Thread ID : 1 Thread ID : 3 Thread ID : 4 Thread ID : 2 Thread ID : 1 Thread ID : 3 Thread ID : 4 Thread ID : 2
From the output you can notice that these threads can run in parallel without waiting for other thread in python. Executing a program is generally associated with a single process . The advantage of multithreading is that concurrency can be used within a process to provide multiple simultaneous services to the user. Multithreading also requires less processing overhead than multiprogramming because concurrent threads are able to share common resources more easily. For more advanced multithreading, see the example..... Multi threaded Socket Programming in Python