NEP -OS lAB B.Sc

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 . . .
DOWNLOAD PDF FILE OS LAB MANUAL

t

 
   
 
 
 
 4.Write a python program to demonstrate Deadlock using threads.
import threading

# Define two locks
lock1 = threading.Lock()
lock2 = threading.Lock()

def thread1():
    print("Thread 1 trying to acquire lock 1")
    lock1.acquire()
    print("Thread 1 acquired lock 1")

    print("Thread 1 trying to acquire lock 2")
    lock2.acquire()
    print("Thread 1 acquired lock 2")

    lock2.release()
    lock1.release()

def thread2():
    print("Thread 2 trying to acquire lock 2")
    lock2.acquire()
    print("Thread 2 acquired lock 2")

    print("Thread 2 trying to acquire lock 1")
    lock1.acquire()
    print("Thread 2 acquired lock 1")

    lock1.release()
    lock2.release()

if __name__ == "__main__":
    # Create two threads
    t1 = threading.Thread(target=thread1)
    t2 = threading.Thread(target=thread2)

    # Start the threads
    t1.start()
    t2.start()

    # Wait for threads to finish
    t1.join()
    t2.join()

    print("Main thread exiting")




Output:
Thread 1 trying to acquire lock 1
Thread 2 trying to acquire lock 2
Thread 2 acquired lock 2
Thread 1 acquired lock 1
Thread 2 trying to acquire lock 1
Thread 1 trying to acquire lock 2