0% found this document useful (0 votes)
4 views7 pages

Unit 3

The document provides an overview of the Python PyLab module, which serves as a procedural interface to the Matplotlib library, allowing for easy plotting and mathematical operations. It details the installation process, basic and advanced plotting techniques, and introduces Python's threading capabilities through the _thread and threading modules, highlighting their features and usage. Additionally, it explains thread synchronization, the lifecycle of threads, and the Queue module for managing multithreaded tasks.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Unit 3

The document provides an overview of the Python PyLab module, which serves as a procedural interface to the Matplotlib library, allowing for easy plotting and mathematical operations. It details the installation process, basic and advanced plotting techniques, and introduces Python's threading capabilities through the _thread and threading modules, highlighting their features and usage. Additionally, it explains thread synchronization, the lifecycle of threads, and the Queue module for managing multithreaded tasks.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python PyLab Module

PyLab is a procedural interface to the Matplotlib object-oriented plotting library.


Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib; and
PyLab is a module that gets installed alongside Matplotlib.

Python PyLab Module

PyLab is a procedural interface to the Matplotlib object-oriented plotting library.


Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib; and
PyLab is a module that gets installed alongside Matplotlib.

PyLab is a convenience module that bulk imports matplotlib.pyplot (for plotting)


and NumPy (for Mathematics and working with arrays) in a single name space.

Installation

The PyLab Module is installed at the same time as the Matplotlib package.
However, if we wish to use this module in a Python program, we must first ensure
that the Matplotlib Module is installed on our system. If Matplotlib is not already
installed on the system, we may use the pip installer command in the command
prompt terminal shell to install Matplotlib Module and so get the PyLab Module

pip install matplotlib

Basic Plotting

Plotting curves is done with the plot() function. It takes a pair of same-length
arrays (or sequences) −

Algorithm (Steps)

Plotting curves is done with the plot() function. It takes a pair of same-length
arrays (or sequences) −

Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −

 Use the import keyword, to import all the functions(represented by *) from the numpy, pylab modules.
 Use the numpy.linspace() function(returns number spaces evenly with respect to the interval) to
generate random points in x-axis
 Get the y-axix values as the square of the x-axis values.
 Plot the x,y values using the plot() function.
 Display the plot using the show() function.

Example
from numpy import *
from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y)
show()

Advanced Plotting

We can utilize some variables in the plot() function, in addition to the x and y
variable arguments, to plot more interactive curves with the PyLab Module. To
print symbol lines instead of straight lines in curves, we must pass additional string
arguments to the plot() function.

Aside from that, we can print the lines in colors other than the default color plotted
in the output curve, and we must follow the same set of instructions to do so.
The color argument must be passed as an additional argument to the plot()
function in order for the line of curve displayed in the output to be printed in the
color of our choice.

To plot symbols rather than lines, provide an additional string argument.

symbols - , –, -., , . , , , o , ^ , v , < , > , s , + , x , D , d , 1 , 2 , 3 , 4 , h , H , p , | , _


colors b, g, r, c, m, y, k, w

numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None)

Parameters

start(optional) − It is the start values of an interval range. Default is 0.

stop − It is the end value of an interval range.

num(optional) − numbers of samples to generate(int)

retstep − If True, then return (samples, step). Restep is set to False by default.

dtype − It is the type of result array

Example
from numpy import *
from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y, 'r.')
show()

Thread Handling Modules in Python

Python's standard library provides two main modules for managing


threads: _thread and threading.

The _thread Module


The _thread module, also known as the low-level thread module, has been a
part of Python's standard library since version 2. It offers a basic API for thread
management, supporting concurrent execution of threads within a shared global
data space. The module includes simple locks (mutexes) for synchronization
purposes.
The threading Module
The threading module, introduced in Python 2.4, builds upon _thread to provide
a higher-level and more comprehensive threading API. It offers powerful tools
for managing threads, making it easier to work with threads in Python
applications.

Key Features of the threading Module

The threading module exposes all the methods of the thread module and
provides some 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.

Starting a New Thread

To create and start a new thread in Python, you can use either the low-
level _thread module or the higher-level threading module. The threading
module is generally recommended due to its additional features and ease of
use. Below, you can see both approaches.

Starting a New Thread Using the _thread Module


The start_new_thread() method of the _thread module provides a basic way to
create and start new threads. This method provides a fast and efficient way to
create new threads in both Linux and Windows. Following is the syntax of the
method −
thread.start_new_thread(function, args[, kwargs] )

This method call returns immediately, and the new thread starts executing the
specified function with the given arguments. When the function returns, the
thread terminates.

Example

import _thread
import time
def print_name(name, *arg):
print(name, *arg)
name="SSSDIIT..."
_thread.start_new_thread(print_name, (name, 1))
_thread.start_new_thread(print_name, (name, 1, 2))
time.sleep(0.5)

Starting a New Thread Using the Threading Module


The threading module provides the Thread class, which is used to create and
manage threads.

Here are a few steps to start a new thread using the threading module −

 Create a function that you want the thread to execute.


 Then create a Thread object using the Thread class by passing the target function
and its arguments.
 Call the start method on the Thread object to begin execution.
 Optionally, call the join method to wait for the thread to complete before
proceeding

Example
import threading
import time
def print_name(name, *args):
print(name, *args)
thread1 = threading.Thread(target=print_name, args=(name, 1))
thread2 = threading.Thread(target=print_name, args=(name, 1, 2))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Threads are finished...exiting")

Synchronizing Threads

The threading module provided with Python includes a simple-to-implement


locking mechanism that allows you to synchronize threads. A new lock is
created by calling the Lock() method, which returns the new lock.

The acquire(blocking) method of the new lock object is used to force threads to
run synchronously. The optional blocking parameter enables you to control
whether the thread waits to acquire the lock.

If blocking is set to 0, the thread returns immediately with a 0 value if the lock
cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1,
the thread blocks and wait for the lock to be released.

The release() method of the new lock object is used to release the lock when it
is no longer required.

Multithreaded Priority Queue

The Queue module allows you to create a new queue object that can hold a
specific number of items. There are following methods to control the Queue −

 get() − The get() removes and returns an item from the queue.
 put() − The put adds item to a queue.
 qsize() − The qsize() returns the number of items that are currently in the queue.
 empty() − The empty( ) returns True if queue is empty; otherwise, False.
 full() − the full() returns True if queue is full; otherwise, False.

A thread object goes through different stages during its life cycle. When a new
thread object is created, it must be started, which calls the run() method of
thread class. This method contains the logic of the process to be performed by
the new thread. The thread completes its task as the run() method is over, and
the newly created thread merges with the main thread.

While a thread is running, it may be paused either for a predefined duration or


it may be asked to pause till a certain event occurs. The thread resumes after
the specified interval or the process is over.

States of a Thread Life Cycle in Python

Following are the stages of the Python Thread life cycle −

 Creating a Thread − To create a new thread in Python, you typically use


the Thread class from the threading module.
 Starting a Thread − Once a thread object is created, it must be started by calling
its start() method. This initiates the thread's activity and invokes its run() method
in a separate thread.
 Paused/Blocked State − Threads can be paused or blocked for various reasons, such
as waiting for I/O operations to complete or another thread to perform a task.
This is typically managed by calling its join() method. This blocks the calling
thread until the thread being joined terminates.
 Synchronizing Threads − Synchronization ensures orderly execution and shared
resource management among threads. This can be done by using synchronization
primitives like locks, semaphores, or condition variables.
 Termination − A thread terminates when its run() method completes execution,
either by finishing its task or encountering an exception.

You might also like