Skip to content

Commit 82fb139

Browse files
Create access_to_resources.py
1 parent d48c443 commit 82fb139

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

scripts/access_to_resources.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import logging
2+
import random
3+
import threading
4+
import time
5+
6+
logging.basicConfig(level=logging.DEBUG,
7+
format='(%(threadName)-10s) %(message)s',
8+
)
9+
10+
class Counter(object):
11+
def __init__(self, start=0):
12+
self.lock = threading.Lock()
13+
self.value = start
14+
def increment(self):
15+
logging.debug('Waiting for lock')
16+
self.lock.acquire()
17+
try:
18+
logging.debug('Acquired lock')
19+
self.value = self.value + 1
20+
finally:
21+
self.lock.release()
22+
23+
def worker(c):
24+
for i in range(2):
25+
pause = random.random()
26+
logging.debug('Sleeping %0.02f', pause)
27+
time.sleep(pause)
28+
c.increment()
29+
logging.debug('Done')
30+
31+
counter = Counter()
32+
for i in range(2):
33+
t = threading.Thread(target=worker, args=(counter,))
34+
t.start()
35+
36+
logging.debug('Waiting for worker threads')
37+
main_thread = threading.currentThread()
38+
for t in threading.enumerate():
39+
if t is not main_thread:
40+
t.join()
41+
logging.debug('Counter: %d', counter.value)

0 commit comments

Comments
 (0)