Simulating a deadlock on a thread

2019-05-13 23:03发布

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 ?

1条回答
闹够了就滚
2楼-- · 2019-05-13 23:12

How can I simulate a deadlock?

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 the sleep(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() to f1, and thread1.join() to f2. Then f1 can't finish until f2 does, f2 can't finish until f1 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.

Also, how can I have each thread run after the other?

Well, the easy way would be to not use threads in the first place. But if you really want, just do this:

thread1.start()
thread1.join()
thread2.start()
thread2.join()
thread3.start()
thread3.join()

Also can I list all the threads that are currently running in my script?

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).

or give them priorities ?

As the docs say:

currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted.

If you want this, you have to step outside of threading and, e.g., use native APIs via ctypes, win32api, etc.

查看更多
登录 后发表回答