-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththr_lock.py
More file actions
47 lines (36 loc) · 762 Bytes
/
Copy paththr_lock.py
File metadata and controls
47 lines (36 loc) · 762 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import threading
import time
RESULT = 0
TIMES = 1000000
lock = threading.Lock()
class Timer(object):
def __init__(self):
self.start = time.time()
def __enter__(self):
pass
def __exit__(self, a, b, c):
end = time.time()
print(end - self.start, ' s')
def incr():
global RESULT, lock
for _ in range(TIMES):
lock.acquire()
print(threading.currentThread().getName())
RESULT += 1
lock.release()
def decr():
global RESULT, lock
for _ in range(TIMES):
lock.acquire()
print(threading.currentThread().getName())
RESULT -= 1
lock.release()
if __name__ == '__main__':
with Timer() as timer:
t1 = threading.Thread(target=incr)
t2 = threading.Thread(target=decr)
t1.start()
t2.start()
t1.join()
t2.join()
print(RESULT)