-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiprocessing_practice.py
More file actions
64 lines (45 loc) · 1.23 KB
/
multiprocessing_practice.py
File metadata and controls
64 lines (45 loc) · 1.23 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from multiprocessing import Process, Lock
import time
def add(a, b):
try:
print("Adding {a}, {b} -> ", a+b)
time.sleep(5)
except Exception as e:
print(e)
def sub(a, b):
try:
print("Subtracting {a}, {b} -> ", a-b)
time.sleep(10)
except Exception as e:
print(e)
def task(lock, identifier, value):
# acquire the lock
lock.acquire()
print(f'>process {identifier} got the lock, sleeping for {value}')
time.sleep(value)
lock.release()
lock.acquire()
print(f'>process {identifier} got the lock again, sleeping for {value}')
time.sleep(value)
lock.release()
def main():
a = 1
b = 2
# add_process = Process(target=add, args=(a, b))
# sub_process = Process(target=sub, args=(a, b))
# ## Starts the processes
# add_process.start()
# sub_process.start()
# ## Waits on the processes to finish
# add_process.join()
# print("waiting on sub")
# sub_process.join()
lock = Lock()
process_1 = Process(target=task, args=(lock, 1, 5))
process_2 = Process(target=task, args=(lock, 2, 2))
process_1.start()
process_2.start()
process_1.join()
process_2.join()
if __name__ == '__main__':
main()