Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 06ed71f

Browse files
Create script21.py
1 parent 82fb139 commit 06ed71f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎scripts/script21.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import logging
2+
import threading
3+
import time
4+
5+
logging.basicConfig(level=logging.DEBUG,
6+
format='(%(threadName)-10s) %(message)s',
7+
)
8+
9+
def lock_holder(lock):
10+
logging.debug('Starting')
11+
while True:
12+
lock.acquire()
13+
try:
14+
logging.debug('Holding')
15+
time.sleep(0.5)
16+
finally:
17+
logging.debug('Not holding')
18+
lock.release()
19+
time.sleep(0.5)
20+
return
21+
22+
def worker(lock):
23+
logging.debug('Starting')
24+
num_tries = 0
25+
num_acquires = 0
26+
while num_acquires < 3:
27+
time.sleep(0.5)
28+
logging.debug('Trying to acquire')
29+
have_it = lock.acquire(0)
30+
try:
31+
num_tries += 1
32+
if have_it:
33+
logging.debug('Iteration %d: Acquired', num_tries)
34+
num_acquires += 1
35+
else:
36+
logging.debug('Iteration %d: Not acquired', num_tries)
37+
finally:
38+
if have_it:
39+
lock.release()
40+
logging.debug('Done after %d iterations', num_tries)
41+
42+
43+
lock = threading.Lock()
44+
45+
holder = threading.Thread(target=lock_holder, args=(lock,), name='LockHolder')
46+
holder.setDaemon(True)
47+
holder.start()
48+
49+
worker = threading.Thread(target=worker, args=(lock,), name='Worker')
50+
worker.start()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /