0% found this document useful (0 votes)
90 views

Ppi Multithreading

This document discusses Python multithreading. It defines a thread as a lightweight process that allows adding concurrency to programs. There are two types of threads in Python: kernel threads and user-space threads. Threads allow for parallel computation, standardization, parallel I/O, and asynchronous events. The threading and thread modules can be used to create threads. Threads share data and processes globally. Synchronization between threads is necessary to prevent race conditions when accessing shared resources. Locks can be used for thread synchronization.

Uploaded by

mani
Copyright
© © All Rights Reserved
0% found this document useful (0 votes)
90 views

Ppi Multithreading

This document discusses Python multithreading. It defines a thread as a lightweight process that allows adding concurrency to programs. There are two types of threads in Python: kernel threads and user-space threads. Threads allow for parallel computation, standardization, parallel I/O, and asynchronous events. The threading and thread modules can be used to create threads. Threads share data and processes globally. Synchronization between threads is necessary to prevent race conditions when accessing shared resources. Locks can be used for thread synchronization.

Uploaded by

mani
Copyright
© © All Rights Reserved
You are on page 1/ 4

Python Multithreading

A thread is a lightweight process or task. A thread is one way to add concurrency to


your programs. If your Python application is using multiple threads and you look at the
processes running on your OS, you would only see a single entry for your script even though it is
running multiple threads.

Threads It is the execution of a tiny sequence of program instruction that can be


managed independently and is a distinctive part of operating system. Modern OS
manage multiple programs using a time-sharing technique.

In Python, there are two different kinds of thread.

1. Kernel Threads
2. User-space threads or User threads
Advantages of Thread:

Thread plays a major role in application programming. All the GUI programs and web
servers are threaded together. The main reasons for using threads are:

 Parallel Computation: If any user has multiprocessor machine then the thread can
allow doing parallel processing with the goal of increase in processing speed.
 Standardization: It became a standard approach for all programming languages
as it increases programming speed.
 Parallel I/O (Input/Output): When we talk about the speed of input & output, it is
comparatively slow in CPU. By placing each i/o operations in multiple individual threads,
programmers can make use of operations done in parallel with each other & with the
computation speed.
 Asynchronous Events: Multiple threaded applications can deal with asynchronous
actions. For example in a program, programmers may don't know whether the next
action will be to use the mouse or to use the keyboard. By planting a separate thread
for each action i.e. two threads both for mouse and keyboard, programmers can able to
code a cleaner, efficient application which is to use non-blocking I/O operations.

Thread Modules In Python

There are two ways of creating Python threads.

1. thread module
2. threading module

NOTE: the module 'thread' treats the thread like a function whereas the 'threading' is
implemented as an object.

Benefits Of Threading
1. For a single process, multiple threads can be used to process and share the same
data-space and can communicate with each other by sharing information.
2. They use lesser memory overhead and hence they are called lightweight
processes.
3. A program can remain responsive to input when threads are used.
4. Threads can share and process the global variable's memory.

In a thread, there are three different parts. It has the beginning, an execution part, and a
conclusion. It also has an instruction pointer that points to where the thread or process is
currently running and hence the thread is able to run several different program blocks
concurrently.

A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest
unit of processing that can be performed in an OS (Operating System).

A thread is a sequence of such instructions within a program that can be executed


independently of other code. You can assume that a thread is simply a subset of a process!
A thread contains all this information in a Thread Control Block (TCB):
 Thread Identifier: Unique id (TID) is assigned to every new thread
 Stack pointer: Points to thread’s stack in the process. Stack contains the local variables
under thread’s scope.
 Program counter: a register which stores the address of the instruction currently being
executed by thread.
 Thread state: can be ready, running, waiting, start or done.
 Thread’s register set: registers assigned to thread for computations.
 Parent process Pointer: A pointer to the Process control block (PCB) of the process that
the thread lives on.
Using A New Thread
Syntax:
thread.start_new_thread(function, args[, kwargs])

Methods Of Thread Class

 start(): is used for starting the thread by calling the run()


 run(): It acts as the entry of the thread
 isAlive(): is used to verify whether the still executing or not
 setName(): is used to set the name of the thread
 getName(): is used for returning the name of a thread
 Join() :When we call this method for any thread, it blocks the
calling thread until the thread whose join()method is called
terminates, either normally or through an unhandled exception

 isDaemon() method
This method is used to get the value of the thread's daemon flag.

 setDaemon(daemonic) method
This method is used to set the thread's daemon flag to the Boolean value daemonic.
This must be called before start() method is called.
The entire Python program exits when no active non-daemon threads are left.

Synchronization between threads


 Thread synchronization is defined as a mechanism which ensures that two or
more concurrent threads do not simultaneously execute some particular program
segment known as critical section.
 Critical section refers to the parts of the program where the shared resource is
accessed.
 For example, in the diagram below, 3 threads try to access shared resource or
critical section at the same time.

 Concurrent accesses to shared resource can lead to race condition.


 A race condition occurs when two or more threads can access shared data and
they try to change it at the same time. As a result, the values of variables may be
unpredictable and vary depending on the timings of context switches of the
processes.

Using Locks

threading module provides a Lock class to deal with the race conditions. Lock is


implemented using a Semaphore object provided by the Operating System.
A semaphore is a synchronization object that controls access by multiple
processes/threads to a common resource in a parallel programming environment. It is
simply a value in a designated place in operating system (or kernel) storage that each
process/thread can check and then change.
Depending on the value that is found, the process/thread can use the resource or will
find that it is already in use and must wait for some period before trying again.
Semaphores can be binary (0 or 1) or can have additional values.
Typically, a process/thread using semaphores checks the value and then, if it using the
resource, changes the value to reflect this so that subsequent semaphore users will
know to wait.
Lock class provides following methods:
 acquire([blocking]) : To acquire a lock. A lock can be blocking or non-blocking.
 When invoked with the blocking argument set to True (the default), thread
execution is blocked until the lock is unlocked, then lock is set to locked and
return True.
 When invoked with the blocking argument set to False, thread execution is
not blocked. If lock is unlocked, then set it to locked and return True else
return False immediately.
 release() : To release a lock.
 When the lock is locked, reset it to unlocked, and return. If any other
threads are blocked waiting for the lock to become unlocked, allow exactly one
of them to proceed.
 If lock is already unlocked, a ThreadError is raised.

Advantages:
 It doesn’t block the user. This is because threads are independent of each other.
 Better use of system resources is possible since threads execute tasks parallely.
 Enhanced performance on multi-processor machines.
 Multi-threaded servers and interactive GUIs use multithreading exclusively.
Disadvantages:
 As number of threads increase, complexity increases.
 Synchronization of shared resources (objects, data) is necessary.
 It is difficult to debug, result is sometimes unpredictable.
 Potential deadlocks which leads to starvation, i.e. some threads may not be
served with a bad design
 Constructing and synchronizing threads is CPU/memory intensive.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy