Python unit - 2 answer bank
Python unit - 2 answer bank
QUESTION BANKS
1.Define thread ?
Threads in python are an entity within a process that can be scheduled
for execution. In simpler words, a thread is a computation process that
is to be performed by a computer.
2. Define join ()
Join in Python is an in-built method used to join an iterable’s elements,
separated by a string separator, which is specified by you. Thus,
whenever you want to join the elements of an iterable and make it a
string, you can use the string join in Python.
5.Define deadlock ?
A deadlock is a situation where two or more threads or processes are
unable to proceed because each is waiting for the other to release a
resource (Lock)
6.Define semaphore ?
A semaphore in Python is a synchronization primitive that manages
access to a shared resource with a limited capacity
7. Define timer ?
A timer in Python is a time-tracking program. Python developers can
create timers with the help of Python's time modules.
EXAMPLE___________
Values = [3,4,5,6]
Def cube(x):
Print(f’Cube of {x}:{x*x*x}’)
If __name__ == ‘__main__’:
Result =[]
With ThreadPoolExecutor(max_workers=5) as exe:
Exe.submit(cube,2)
Result = exe.map(cube,values)
For r in result:
Print(r)
. OUTPUT
Cube of 2:8
Cube of 3:27
Cube of 4:64
Cube of 5:125
Cube of 6:216
1. Creating a Thread:
To create a thread, you can instantiate a Thread object from the threading
module. You provide the target function (the function the thread will run) and
optionally arguments.
Import threading
Def print_numbers():
For I in range(5):
Print(i)
# Create a thread that runs the print_numbers function
Thread = threading.Thread(target=print_numbers)
Thread.start()
Thread.join()
You can create and run multiple threads by following the same process. If
you need to run the same function with different arguments, you can pass
those arguments to the thread.
Import threading
Def print_numbers(thread_name):
For I in range(5):
Print(f”{thread_name}: {i}”)
Thread1.start()
Thread2.start()
Thread1.join()
Thread2.join()
In this example:
3.Thread Synchronization:
Import threading
# Shared resource
Counter = 0
Lock = threading.Lock()
Def increment():
Global counter
With lock: # Ensures only one thread accesses this block at a time
Temp = counter
Temp += 1
Counter = temp
Thread.start()
Thread.join()
Print(f”Final counter value: {counter}”)
In this example:
A Lock is used to ensure that only one thread can modify the shared counter
variable at a time, preventing race conditions.
4.Thread Safety:
While Python’s Global Interpreter Lock (GIL) limits true parallelism in CPU-
bound operations, threads are still useful for I/O-bound tasks (such as
network or file operations) where the GIL is released during blocking I/O calls.
5.Daemon Threads:
Import threading
Import time
Def background_task():
While True:
Time.sleep(1)
Daemon_thread.start()
# Main program exits after 5 seconds, even though the daemon thread is still
running
Time.sleep(5)
1. Mutual Exclusion
3. No Preemption
4. Circular Wait
Deadlock Example
Both processes are stuck because they cannot proceed until the other
releases its resource.
Methods for Handling Deadlocks
1. Deadlock Prevention
Ensure that at least one of the four conditions for deadlock cannot occur. For
instance:
2. Deadlock Avoidance
Use algorithms like the Banker's Algorithm to ensure that resource allocation
does not lead to a deadlock.
Allow the system to enter a deadlock state and then detect it using a
resource allocation graph or similar methods. Once detected:
In some systems, such as personal computers, deadlocks are rare and may
be ignored, relying on a system reboot to resolve the issue.
10 marks :
- The producer threads can produce data at their own pace without
worrying about the consumer threads
- The consumer threads can consume data at their own pace without
worrying about the producer threads
- The queue is used efficiently and doesn’t overflow or underflow
Components:
Problem Statement:
Solution:
Protocol:
Synchronization Techniques:
Benefits:
Example:
- Producer threads: web servers generating HTML pages
- Consumer threads: web browsers rendering HTML pages
- Queue: a buffer that stores HTML pages
- The producer threads can produce data at their own pace without
worrying about the consumer threads.
- The consumer threads can consume data at their own pace without
worrying about the producer threads.
- The shared buffer does not overflow or underflow.
2.Producer Thread:
a. Produce data.
b. Put data into the queue using `put(item)`.
c. If the queue is full, wait until the consumer thread consumes some
data.
3.Consumer Thread:
4. Synchronization:
a. If the queue is full, the producer thread waits until the consumer
thread consumes some data.
b. If the queue is empty, the consumer thread waits until the producer
thread produces some data.
Using a queue ensures that the producer and consumer threads are
decoupled, and the shared buffer does not overflow or underflow.
Example :
Import queue
Import threading
Import time
How it works :
Semaphore Methods:
- `acquire()`: Decrement the semaphore value. If the value is zero, block
until another thread releases the semaphore.
Example:
```
Import threading
Import time
Def worker():
Sem.acquire()
Try:
Print(“Working…”)
Time.sleep(2)
Finally:
Sem.release()
Threads = []
For I in range(6):
T = threading.Thread(target=worker)
Threads.append(t)
t.start()
for t in threads:
t.join()
```
- The producer threads can produce data at their own pace without
worrying about the consumer threads.
- The consumer threads can consume data at their own pace without
worrying about the producer threads.
- The shared buffer does not overflow or underflow.
3. Producer Thread:
1. Consumer Thread:
1. Synchronization:
a. If the shared buffer is full, the producer thread waits until the
consumer thread consumes some data.
b. If the shared buffer is empty, the consumer thread waits until the
producer thread produces some data.
Using a lock ensures that only one thread can access the shared buffer
at a time, preventing data corruption and ensuring synchronization.
# Lock (mutex)
Lock = threading.Lock()
# Producer thread function
Def producer():
For I in range(10):
With lock:
While q.full():
Lock.wait()
q.put(i)
print(“Produced:”, i)
lock.notify()
time.sleep(0.1)