python:使用GIL,线程还可能出现死锁吗? (不是多重处理)

问题描述 投票:0回答:1

python:使用GIL,线程还可能出现死锁吗? (不是多重处理)

我试图产生死锁情况,但下面的代码并没有造成死锁。

import threading

# Two resources
resource1 = threading.Lock()
resource2 = threading.Lock()

def function1():
    with resource1:
        print("Thread 1 acquired resource 1")
        # Simulate some computation
        with resource2:
            print("Thread 1 acquired resource 2")
            # Do something with both resources
            pass

def function2():
    with resource2:
        print("Thread 2 acquired resource 2")
        # Simulate some computation
        with resource1:
            print("Thread 2 acquired resource 1")
            # Do something with both resources
            pass

# Create two threads
thread1 = threading.Thread(target=function1)
thread2 = threading.Thread(target=function2)

# Start the threads
thread1.start()
thread2.start()

# Wait for both threads to finish
thread1.join()
thread2.join()

print("Both threads finished execution")
python multithreading gil
1个回答
0
投票

你的代码可以死锁(它至少在一次运行中为我做到了),但这取决于另一个线程在另一个线程的两个

with resource
语句之间执行
with resource
。如果这个特定的时间没有发生,它就不会锁定。显然,如果代码有任何机会出现死锁,那么它就是糟糕的代码,但要注意到它并不那么容易。

为了确保死锁,请尝试将

time.sleep(1)
放在每个函数中的两个
with resource
语句之间。

© www.soinside.com 2019 - 2024. All rights reserved.