死锁示例(python、go)
Thread 1首先获取了资源A,然后尝试获取资源B,但此时资源B已经被Thread 2获取,因此Thread 1会一直等待。而Thread 2也类似,首先获取资源B,然后尝试获取资源A,但此时资源A已经被Thread 1获取,因此Thread 2也会一直等待。这样就形成了典型的死锁情况。
import threading
import time# 创建两个资源
resource_a = threading.Lock()
resource_b = threading.Lock()def thread1():with resource_a:print("Thread 1 acquired resource A")# 模拟一些操作time.sleep(1)print("Thread 1 is working...")# 尝试获取资源B,但此时资源B被Thread 2持有,导致Thread 1等待with resource_b:print("Thread 1 acquired resource B")# 模拟一些操作print("Thread 1 is working...")def thread2():with resource_b:print("Thread 2 acquired resource B")# 模拟一些操作time.sleep(1)print("Thread 2 is working...")# 尝试获取资源A,但此时资源A被Thread 1持有,导致Thread 2等待with resource_a:print("Thread 2 acquired resource A")# 模拟一些操作print("Thread 2 is working...")# 创建两个线程并启动
t1 = threading.Thread(target=thread1)
t2 = threading.Thread(target=thread2)
t1.start()
t2.start()
package mainimport ("fmt""sync"
)func main() {var wg sync.WaitGroupch1 := make(chan bool)ch2 := make(chan bool)wg.Add(2)// Goroutine 1go func() {defer wg.Done()<-ch1 // 等待 Goroutine 2 发送数据到 ch1fmt.Println("Goroutine 1 received data from Goroutine 2")// 尝试向 ch2 发送数据,但 Goroutine 2 已经在等待 ch1ch2 <- truefmt.Println("Goroutine 1 sent data to Goroutine 2")}()// Goroutine 2go func() {defer wg.Done()<-ch2 // 等待 Goroutine 1 发送数据到 ch2fmt.Println("Goroutine 2 received data from Goroutine 1")// 尝试向 ch1 发送数据,但 Goroutine 1 已经在等待 ch2ch1 <- truefmt.Println("Goroutine 2 sent data to Goroutine 1")}()wg.Wait()
}