Question

Give a programming example in python of a deadlock with semaphore lock. please include output screenshot.

Give a programming example in python of a deadlock with semaphore lock. please include output screenshot.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

# TEXT CODE STARTS HERE

# import threading module to use Semaphore
import threading

#import time to make thread sleep for specified time
import time

# create two semaphores sem1 and sem2
sem1 = threading.Semaphore()
sem2 = threading.Semaphore()


# defining method fun1() to run in thread t1
# thread t1 will try to acquire locks in order sem1 then sem2
def fun1():
   # print some message about thread1
print("Thread1 started")

while True:
       # acquire lock on sem1
sem1.acquire()

# make thread t1 to sleep for 1 sec.
time.sleep(1)

# qcquire lock on sem2
sem2.acquire()

# print string "THREAD1"
print("THREAD1")

# release lock on sem2
sem2.release()

# release lock on sem1
sem1.release()



# defining method fun1() to run in thread t2
# thread t2 will try to acquire locks in order sem2 then sem1
def fun2():
   # print some message about thread2
print("Thread2 sarted")

while True:
   # acquire lock on sem2
sem2.acquire()

# make thread t2 to sleep for 1 sec.
time.sleep(1)

# qcquire lock on sem1
sem1.acquire()

# print string "THREAD2"
print("THREAD2")

# release lock on sem1
sem1.release()

# release lock on sem2
sem2.release()

  
# create thread t1 with target method fun1
t1 = threading.Thread(target = fun1)

# start thread t1
t1.start()

# create thread t1 with target method fun1
t2 = threading.Thread(target = fun2)

# start thread t1
t2.start()

# TEXT CODE ENDS HERE

SCREENSHOTS:

code:

output ( Thread1 and Thread2 has successfully started but fall in deadlock ) :

NOTE:-

Add a comment
Know the answer?
Add Answer to:
Give a programming example in python of a deadlock with semaphore lock. please include output screenshot.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT