- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson04_mutex_lock.py
More file actions
Latest commit
29 lines (27 loc) · 869 Bytes
/
Copy pathlesson04_mutex_lock.py
File metadata and controls
29 lines (27 loc) · 869 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
# SuperFastPython.com
# example of protecting a critical section with a mutex
fromtimeimportsleep
fromrandomimportrandom
fromthreadingimportThread
fromthreadingimportLock
# custom function to be executed in a new thread
deftask(shared_lock, ident, value):
# acquire the lock
withshared_lock:
# report a message
print(f'>{ident} got lock, sleeping {value}')
# block for a fraction of a second
sleep(value)
# protect the entry point
if__name__=='__main__':
# create the shared mutex lock
lock=Lock()
# create a number of threads with different args
threads= [Thread(target=task,
args=(lock, i, random())) foriinrange(10)]
# start the threads
forthreadinthreads:
thread.start()
# wait for all threads to finish
forthreadinthreads:
thread.join()