-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocks.py
More file actions
34 lines (31 loc) · 939 Bytes
/
locks.py
File metadata and controls
34 lines (31 loc) · 939 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
# SuperFastPython.com
# example of a reentrant lock for processes
from time import sleep
from random import random
from multiprocessing import Process
from multiprocessing import RLock, Lock, Semaphore
# reporting function
def report(lock, identifier):
# acquire the lock
with lock:
print(f'>process {identifier} done')
# work function
def task(lock, identifier, value):
# acquire the lock
with lock:
print(f'>process {identifier} sleeping for {value}')
sleep(value)
# report
report(lock, identifier)
# entry point
if __name__ == '__main__':
# create a shared reentrant lock
lock = RLock()
# create processes
processes = [Process(target=task, args=(lock, i, random())) for i in range(10)]
# start child processes
for process in processes:
process.start()
# wait for child processes to finish
for process in processes:
process.join()