0% found this document useful (0 votes)
5 views18 pages

Python Programming Unit 3

This document covers Regular Expressions and Python Multithreaded Programming, explaining the use of regex for text manipulation and the concepts of threads and processes in Python. It details special symbols in regex, the functionality of the re module, and the differences between single-threaded and multithreaded programs. Additionally, it discusses the Global Interpreter Lock (GIL) in Python and provides insights into using the threading and _thread modules for managing threads.

Uploaded by

motatiakhila
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)
5 views18 pages

Python Programming Unit 3

This document covers Regular Expressions and Python Multithreaded Programming, explaining the use of regex for text manipulation and the concepts of threads and processes in Python. It details special symbols in regex, the functionality of the re module, and the differences between single-threaded and multithreaded programs. Additionally, it discusses the Global Interpreter Lock (GIL) in Python and provides insights into using the threading and _thread modules for managing threads.

Uploaded by

motatiakhila
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

UNIT - III Regular Expressions: Introduction, Special Symbols and Characters, Res and

Python Multithreaded Programming: Introduction, Threads and Processes, Python, Threads,


and the Global Interpreter Lock, Thread Module, Threading Module, Related Modules

Regular Expressions
Regular Expressions (Regex) are patterns of characters used to search, match, and manipulate text.
They help in finding specific patterns such as words, numbers, email IDs, phone numbers, or formats
within strings.
In Python, regular expressions are implemented using the re module. Regex is commonly used for
input validation, text searching, data extraction, and text replacement. It provides a powerful and
flexible way to handle string operations efficiently.
Example use: checking whether an email address or mobile number is in the correct format.

Special Symbols and Characters (Regular Expressions)


Special symbols and characters in regular expressions are called metacharacters. They have special
meanings and are used to define search patterns.
Common Special Symbols:
• . → Matches any single character
• ^ → Matches the beginning of a string
• $ → Matches the end of a string
• * → Matches zero or more occurrences
• + → Matches one or more occurrences
• ? → Matches zero or one occurrence
• [] → Matches any one character inside the brackets
• () → Used for grouping patterns
• | → Acts as OR operator
These symbols make pattern matching powerful and flexible for searching and validating text.
1. Dot ( . )
Matches any single character except newline.
Example:
import re
[Link]("c.t", "cat") # Matches
2. Caret ( ^ )
Matches the start of a string.
Example:
[Link]("^Hello", "Hello World") # Matches

3. Dollar ( $ )
Matches the end of a string.
Example:
[Link]("end$", "This is the end") # Matches

4. Asterisk ( * )
Matches zero or more occurrences of preceding character.
Example:
[Link]("lo*", "l") # Matches

5. Plus ( + )
Matches one or more occurrences.
Example:
[Link]("lo+", "loo") # Matches

6. Question Mark ( ? )
Matches zero or one occurrence.
Example:
[Link]("colou?r", "color") # Matches

7. Square Brackets ( [] )
Matches any one character inside brackets.
Example:
[Link]("[aeiou]", "sky") # No match

8. Parentheses ( () )
Used for grouping patterns.
Example:
[Link]("(ab)+", "abab") # Matches
9. OR Operator ( | )
Matches either one pattern or another.
Example:
[Link]("cat|dog", "I have a dog") # Matches

10. Digit Character ( \d )


Matches any digit (0–9).
Example:
[Link]("\d", "Room 5") # Matches

Res (Regular Expressions) and Python


In Python, Regular Expressions are supported through the re module. This module provides a
complete set of tools to work with pattern matching and text processing. It allows programmers to
search, extract, replace, and manipulate strings efficiently using defined patterns.
To use regular expressions in Python, the re module must be imported:
import re

1. Pattern and String


• A pattern is a regular expression written using special symbols and characters.
• The string is the text in which the pattern is searched.
Example:
pattern = "Python"
text = "Python is easy"

2. [Link]()
• Checks whether the pattern matches only at the beginning of the string.
• Returns a match object if successful, otherwise returns None.
Example:
[Link]("Python", "Python is powerful") # Match found
[Link]("power", "Python is powerful") # No match

3. [Link]()
• Searches the entire string for the pattern.
• Returns the first occurrence of the match.
Example:
[Link]("power", "Python is powerful")

4. [Link]()
• Finds all occurrences of the pattern.
• Returns a list of matches.
Example:
[Link]("\d", "Marks: 80, 90, 85")

5. [Link]()
• Similar to findall(), but returns an iterator of match objects.
• Useful when match position is required.
Example:
for m in [Link]("is", "This is Python"):
print([Link](), [Link]())

6. [Link]()
• Replaces the matched pattern with another string.
Example:
[Link]("\s", "-", "Python is fun")

7. [Link]()
• Splits a string based on a regex pattern.
Example:
[Link](",", "apple,banana,orange")

8. Match Object Methods


When a match is found, a match object is returned.

Method Description

group() Returns matched string

start() Starting index


Method Description

end() Ending index

span() Start and end index

Example:
m = [Link]("Python", "I love Python")
print([Link]())

9. Flags in re Module
Flags modify the behavior of regex matching.

Flag Description

re.I Ignore case

re.M Multiline mode

re.S Dot matches newline

Example:
[Link]("python", "PYTHON", re.I)

Multithreaded Programming
Multithreaded programming is a programming technique in which a single program is divided into
multiple smaller units called threads that can execute concurrently. These threads run within the
same process and share the same memory space, which helps in faster execution and efficient
resource utilization.

What is a Thread?
A thread is the smallest unit of execution in a program.
• A process can have multiple threads
• All threads share:
o Code section
o Data section
o Heap memory
• Each thread has its own:
o Program counter
o Stack
o Registers

Why Multithreading is Needed


Multithreading is mainly used to:
• Improve program performance
• Perform multiple tasks simultaneously
• Keep applications responsive
• Efficiently handle I/O operations
Example:
• One thread reads data from a file
• Another thread processes the data
• Another thread displays output

Single-threaded vs Multithreaded Program

Single-threaded Multithreaded

Executes one task at a time Executes multiple tasks at a time

Slower execution Faster execution

Program may freeze during I/O Program remains responsive

Poor CPU utilization Better CPU utilization

Applications of Multithreading
• Web servers
• Operating systems
• Multimedia applications
• Games
• Network communication
• GUI applications
Threads and Processes
In operating systems and programming, processes and threads are used to achieve concurrent
execution. Though both help in running multiple tasks, they differ in structure, memory usage, and
execution style.
1. Process
A process is an independent program that is currently running.
Key Features of a Process
• Has its own memory space
• Runs independently of other processes
• Requires more system resources
• Communication between processes is slow
• More secure and stable
Real-Life Example
When you open:
• Google Chrome
• MS Word
• Music Player
Each application runs as a separate process.
Python Example (Process)
from multiprocessing import Process
def task():
print("This is a process")
p = Process(target=task)
[Link]()
[Link]()
Here, task() runs in a separate process with its own memory.

2. Thread
A thread is a lightweight unit of execution that runs inside a process.
Key Features of a Thread
• Shares memory with other threads
• Faster execution
• Uses fewer resources
• Communication is easy
• Less secure than processes
Real-Life Example
In a web browser:
• One thread loads a webpage
• Another thread plays a video
• Another thread handles user input
All these threads belong to one browser process.
Python Example (Thread)
import threading
def task():
print("This is a thread")
t = [Link](target=task)
[Link]()
[Link]()
Here, task() runs as a thread inside the same process.

3. Process vs Thread (Detailed Comparison)

Feature Process Thread

Unit Independent program Part of a process

Memory Separate memory Shared memory

Creation Slow Fast

Communication IPC required Shared memory

Resource usage High Low

Isolation Strong Weak

Failure Does not affect others Affects whole process

4. Context Switching
• Process switching is slow because memory changes
• Thread switching is faster due to shared memory
5. When to Use What
Use Processes When:
• CPU-bound tasks
• True parallelism required
• High stability is needed
Use Threads When:
• I/O-bound tasks
• Fast response required
• Shared data is needed

6. Simple Example Showing Difference


Thread Example (Shared Memory)
import threading
x=0
def increment():
global x
x += 1
t1 = [Link](target=increment)
t2 = [Link](target=increment)
[Link]()
[Link]()
Threads share the same variable x.

Process Example (Separate Memory)


from multiprocessing import Process
x=0
def increment():
global x
x += 1
print(x)
p1 = Process(target=increment)
p2 = Process(target=increment)
[Link]()
[Link]()
Each process has its own copy of x.

Python, Threads, and the Global Interpreter Lock (GIL)


Python supports multithreading, but its behavior is strongly influenced by a mechanism called the
Global Interpreter Lock (GIL). Understanding the relationship between Python threads and the
GIL is essential to know when multithreading is effective and when it is not.

1. Python Threads
• Python allows creation of threads using the threading module.
• Multiple threads can be created within a single process.
• Threads share the same memory space, making data sharing easy.
• Python threads are mainly useful for I/O-bound tasks (file operations, network calls,
database access).

2. What is the Global Interpreter Lock (GIL)?


The Global Interpreter Lock (GIL) is a mutex (lock) used by the CPython interpreter.
Purpose of GIL
• Ensures that only one thread executes Python bytecode at a time
• Protects Python’s memory management system
• Prevents data corruption in multi-threaded programs
Even on multi-core CPUs, only one thread can execute Python code at any instant due to the GIL.

3. How GIL Works


• When a thread wants to execute Python code, it must acquire the GIL
• Other threads must wait until the GIL is released
• The GIL is periodically released so other threads can run
This gives an illusion of parallelism, not true parallel execution.

4. Effect of GIL on Performance


CPU-Bound Tasks
• Tasks that require heavy computation
• GIL becomes a bottleneck
• Threads do not improve performance
Example (CPU-bound):
import threading
def compute():
for i in range(10**7):
pass
t1 = [Link](target=compute)
t2 = [Link](target=compute)
[Link]()
[Link]()
Both threads run one after another, not in parallel.

I/O-Bound Tasks
• Tasks that wait for input/output operations
• GIL is released during I/O wait
• Threads improve performance
Example (I/O-bound):
import threading
import time
def io_task():
[Link](2)
print("Task completed")
t1 = [Link](target=io_task)
t2 = [Link](target=io_task)
[Link]()
[Link]()
Both threads overlap during waiting time.

5. Why GIL Exists


• Makes Python simple and stable
• Ensures thread safety
• Improves performance for single-threaded programs
• Simplifies memory management

6. How to Overcome GIL Limitation


• Use multiprocessing for CPU-bound tasks
• Use C extensions that release the GIL
• Use async programming (asyncio) for I/O-bound tasks

Thread Module (_thread)


The Thread module in Python, called _thread, is a low-level module used to create and manage
threads directly. It provides basic threading support, but offers limited control compared to the
threading module.

1. Introduction to Thread Module


• _thread is the primitive threading module in Python.
• It allows creation of threads using simple functions.
• It does not support thread classes or advanced features.
• Mainly used for simple or learning purposes.
Importing the module
import _thread

2. Creating a Thread
Threads are created using the start_new_thread() function.
Syntax
_thread.start_new_thread(function, args)
• function → function to be executed
• args → tuple of arguments
Example
import _thread
import time
def display():
print("Thread is running")
_thread.start_new_thread(display, ())
[Link](1)
Here, a new thread is created to execute the display() function.

3. Important Functions in _thread Module

Function Description

start_new_thread() Starts a new thread

allocate_lock() Creates a lock object

exit() Exits the thread

get_ident() Returns thread identifier

4. Synchronization Using Lock


Locks are used to prevent race conditions.
Example
lock = _thread.allocate_lock()
def task():
[Link]()
print("Critical section")
[Link]()

5. Limitations of Thread Module


• No thread objects
• No join() method
• Hard to manage thread lifecycle
• Error handling is difficult
• Not suitable for large applications

6. When to Use Thread Module


• Simple programs
• Educational purposes
• Very basic threading needs
7. Comparison with threading Module

Thread Module Threading Module

Low-level High-level

Limited features Rich features

Difficult to manage Easy to manage

Not recommended Recommended

Threading Module
The threading module in Python is a high-level module used to create and manage threads easily. It
is built on top of the low-level _thread module and provides better control, safety, and flexibility.
Because of its rich features, it is the most commonly used module for multithreading in Python.

1. Introduction to Threading Module


• Provides an object-oriented approach to threading
• Easier and safer than _thread
• Supports thread synchronization and communication
• Widely used in real-world applications
Importing the module
import threading

2. Creating a Thread
Threads are created using the Thread class.
Syntax
[Link](target=function_name, args=(arguments,))
Example
import threading
def task():
print("Thread is running")
t = [Link](target=task)
[Link]()
[Link]()
• start() → begins thread execution
• join() → waits for thread to finish

3. Thread Class Methods

Method Purpose

start() Starts the thread

run() Contains thread code

join() Waits for thread completion

is_alive() Checks if thread is active

getName() Returns thread name

setName() Sets thread name

4. Creating Thread Using Class


A thread can also be created by extending the Thread class.
class MyThread([Link]):
def run(self):
print("Thread using class")
t = MyThread()
[Link]()

5. Thread Synchronization
When multiple threads access shared data, synchronization is required.
Lock
lock = [Link]()
def task():
[Link]()
print("Critical section")
[Link]()
Locks prevent race conditions.
6. Daemon Threads
• Background threads
• Automatically terminate when main program exits
[Link](True)

7. Thread Lifecycle
1. New
2. Runnable
3. Running
4. Blocked
5. Terminated

8. Advantages of Threading Module


• Easy to use
• Better thread management
• Built-in synchronization tools
• Safer than _thread

9. Limitations
• Limited by Global Interpreter Lock (GIL)
• Not suitable for CPU-bound tasks

Related Modules
1. queue Module
The queue module is used for thread-safe communication between threads.
Features
• Avoids race conditions
• Commonly used in producer–consumer problems
• Automatically handles locking
Types of Queues
• Queue() – FIFO
• LifoQueue() – Stack
• PriorityQueue() – Priority based
Example
from queue import Queue
q = Queue()
[Link](10)
print([Link]())
Use
• Data exchange between threads
• Safe multithreading

4. Mutex (Mutual Exclusion)


A mutex is a locking mechanism that ensures only one thread accesses a shared resource at a time.
Why Mutex is Needed
• Prevents race conditions
• Protects shared data
Python Mutex
Implemented using Lock from threading module.
Example
import threading
lock = [Link]()
def critical():
[Link]()
print("Inside critical section")
[Link]()
Important Point
• Only one thread can hold the lock at a time

5. Socket Server
A socket server allows network communication between a server and multiple clients.
Socket Module
Python provides the socket module.
Basic Working
1. Server creates a socket
2. Server listens for client requests
3. Client connects to server
4. Data is exchanged
Simple Server Example
import socket
s = [Link]()
[Link](('localhost', 1234))
[Link](1)
conn, addr = [Link]()
print("Connected by", addr)
[Link](b"Hello Client")
[Link]()
Applications
• Chat applications
• Web servers
• File transfer systems

You might also like