I have 3 threads, that are currently running simultaneously.
def f1():
print "running first thread\n"
sleep(10)
def f2():
print "running second thread\n"
sleep(10)
def f3():
print "running third thread\n"
sleep(10)
if __name__ == "__main__":
thread1 = Thread(target = f1)
thread2 = Thread(target = f2)
thread3 = Thread(target = f3)
try:
thread1 = Thread(target = f1)
thread1.start()
thread2 = Thread(target = f2)
thread2.start()
thread3 = Thread(target = f3)
thread3.start()
while(thread1.isAlive() or thread2.isAlive() or thread3.isAlive()):
thread1.join()
thread2.join()
thread3.join()
except (KeyboardInterrupt, SystemExit):
sys.exit()
How can I simulate a deadlock? Also, how can I have each thread run after the other? Also can I list all the threads that are currently running in my script? or give them priorities ?
All a deadlock means is that one or more threads are blocked from making any progress, so you can simulate it with a single thread. Just put a
while True:
around thesleep(10)
.In realistic cases, you usually have two threads blocking each other from progress at the same time. For example, maybe they've taken a pair of locks in reverse order, so thread 1 won't release lock 1 until it gets lock 2, but thread 2 won't release lock 2 until it gets lock 1. So, it might be better to simulate it by having two threads block permanently.
If you want to actually create a deadlock, the simplest way is to have the threads literally block on each other: add
thread2.join()
tof1
, andthread1.join()
tof2
. Thenf1
can't finish untilf2
does,f2
can't finish untilf1
does, so neither one can ever finish.However, if you want to create a realistic deadlock, you will almost certainly want to use synchronization objects like
threading.Lock
to do something like the two-lock scenario described above.Well, the easy way would be to not use threads in the first place. But if you really want, just do this:
See threading.enumerate(). You usually don't want to use this except for debugging purposes; keep track of the threads as you create them, if you want to have access to them later (as you're doing).
As the docs say:
If you want this, you have to step outside of
threading
and, e.g., use native APIs viactypes
,win32api
, etc.