Skip to content

Commit 9303d68

Browse files
Create locks_as_cont_manager.py
1 parent 3a6d4cd commit 9303d68

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

scripts/locks_as_cont_manager.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import threading
2+
import logging
3+
4+
logging.basicConfig(level=logging.DEBUG,
5+
format='(%(threadName)-10s) %(message)s',
6+
)
7+
8+
def worker_with(lock):
9+
with lock:
10+
logging.debug('Lock acquired via with')
11+
12+
def worker_no_with(lock):
13+
lock.acquire()
14+
try:
15+
logging.debug('Lock acquired directly')
16+
finally:
17+
lock.release()
18+
19+
lock = threading.Lock()
20+
w = threading.Thread(target=worker_with, args=(lock,))
21+
nw = threading.Thread(target=worker_no_with, args=(lock,))
22+
23+
w.start()
24+
nw.start()

0 commit comments

Comments
 (0)