Skip to content

Instantly share code, notes, and snippets.

@huangsam
Last active November 4, 2024 21:55
Show Gist options
  • Save huangsam/33748e0901269bf4b46fb9c04cbb314f to your computer and use it in GitHub Desktop.
Save huangsam/33748e0901269bf4b46fb9c04cbb314f to your computer and use it in GitHub Desktop.
Deadlock stuff
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()
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();
}
}
@huangsam
Copy link
Author

huangsam commented Nov 4, 2024

Some examples just to show how it can happen in Python and Java.

How to Avoid Deadlocks:

  • Consistent Locking Order: Ensure threads acquire locks in the same order to avoid circular dependencies.
  • Timeouts: Use timeouts on lock acquisition to prevent indefinite waiting.
  • Hierarchy of Locks: Establish a hierarchy of locks and acquire them in a specific order.
  • Careful Design: Consider the potential for deadlocks during system design and implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment