forked from jwasham/practice-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads2.py
More file actions
47 lines (30 loc) · 717 Bytes
/
threads2.py
File metadata and controls
47 lines (30 loc) · 717 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 random
import threading
import time
def synchronize(func):
def lock_resource(*args, **kwargs):
global lock
lock.acquire()
try:
func(*args, **kwargs)
finally:
lock.release()
return lock_resource
@synchronize
def count_up(num):
global database
time.sleep(random.randrange(3))
database.append(num)
def main():
global database, lock
lock = threading.Lock()
database = []
threads = []
for i in range(15):
threads.append(threading.Thread(target=count_up, args=(i+1,)))
threads[i].start()
for th in threads:
th.join()
print(database)
if __name__ == '__main__':
main()