-
Notifications
You must be signed in to change notification settings - Fork 45
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve deadlock tutorial documentation about use of locals argument
Signed-off-by: Matheus Nascimento <[email protected]>
- Loading branch information
1 parent
8d2a5f7
commit 7b6b5a1
Showing
2 changed files
with
133 additions
and
69 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,48 +1,30 @@ | ||
#!/usr/bin/env | ||
|
||
import os | ||
import threading | ||
import time | ||
|
||
|
||
def first_thread(lock1, lock2): | ||
print("Thread 1: Trying to acquire lock1") | ||
def background(lock1, lock2): | ||
with lock1: | ||
print("Thread 1: lock1 acquired") | ||
|
||
print(" First lock acquired") | ||
time.sleep(1) | ||
|
||
print("Thread 1: Trying to acquire lock2") | ||
with lock2: | ||
print("Thread 1: lock2 acquired") | ||
print("Thread 1: Released both locks") | ||
|
||
|
||
def second_thread(lock1, lock2): | ||
print("Thread 2: Trying to acquire lock2") | ||
with lock2: | ||
print("Thread 2: lock2 acquired") | ||
|
||
time.sleep(1) | ||
|
||
print("Thread 2: Trying to acquire lock1") | ||
with lock1: | ||
print("Thread 2: lock1 acquired") | ||
print("Thread 2: Released both locks") | ||
print(" Second lock acquired") | ||
|
||
|
||
if __name__ == "__main__": | ||
print(f"thread ID {os.getpid()}") | ||
print(f"Process ID: {os.getpid()}") | ||
lock1 = threading.Lock() | ||
lock2 = threading.Lock() | ||
|
||
p1 = threading.Thread(target=first_thread, args=(lock1, lock2)) | ||
p2 = threading.Thread(target=second_thread, args=(lock1, lock2)) | ||
t1 = threading.Thread(target=background, args=(lock1, lock2)) | ||
t2 = threading.Thread(target=background, args=(lock2, lock1)) | ||
|
||
p1.start() | ||
p2.start() | ||
print("Stating First Thread") | ||
t1.start() | ||
print("Stating Second Thread") | ||
t2.start() | ||
|
||
p1.join() | ||
p2.join() | ||
t1.join() | ||
t2.join() | ||
|
||
print("Finished execution") |
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