Last active
November 4, 2024 21:55
-
-
Save huangsam/33748e0901269bf4b46fb9c04cbb314f to your computer and use it in GitHub Desktop.
Deadlock stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
lock1 = threading.Lock() | |
lock2 = threading.Lock() | |
def thread1(): | |
lock1.acquire() | |
print("Thread 1: Acquired lock1") | |
time.sleep(0.5) | |
try: | |
lock2.acquire() | |
print("Thread 1: Acquired lock2") | |
finally: | |
lock2.release() | |
lock1.release() | |
def thread2(): | |
lock2.acquire() | |
print("Thread 2: Acquired lock2") | |
time.sleep(1) | |
try: | |
lock1.acquire() | |
print("Thread 2: Acquired lock1") | |
finally: | |
lock1.release() | |
lock2.release() | |
t1 = threading.Thread(target=thread1) | |
t2 = threading.Thread(target=thread2) | |
t1.start() | |
t2.start() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DeadlockExample { | |
public static void main(String[] args) { | |
Object lock1 = new Object(); | |
Object lock2 = new Object(); | |
Thread thread1 = new Thread(() -> { | |
synchronized (lock1) { | |
System.out.println("Thread 1: Acquired lock1"); | |
try { | |
Thread.sleep(1000); | |
// Simulate work | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
synchronized (lock2) { | |
System.out.println("Thread 1: Acquired lock2"); | |
} | |
} | |
}); | |
Thread thread2 = new Thread(() -> { | |
synchronized (lock2) { | |
System.out.println("Thread 2: Acquired lock2"); | |
try { | |
Thread.sleep(1000); | |
// Simulate work | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
synchronized (lock1) { | |
System.out.println("Thread 2: Acquired lock1"); | |
} | |
} | |
}); | |
thread1.start(); | |
thread2.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some examples just to show how it can happen in Python and Java.
How to Avoid Deadlocks: