- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson04_semaphore.py
More file actions
Latest commit
31 lines (29 loc) · 920 Bytes
/
Copy pathlesson04_semaphore.py
File metadata and controls
31 lines (29 loc) · 920 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
# SuperFastPython.com
# example of a semaphore to limit access to resource
fromtimeimportsleep
fromrandomimportrandom
fromthreadingimportThread
fromthreadingimportSemaphore
# custom function to be executed in a new thread
deftask(shared_semaphore, ident):
# attempt to acquire the semaphore
withshared_semaphore:
# generate a random value between 0 and 1
val=random()
# block for a fraction of a second
sleep(val)
# report result
print(f'Thread {ident} got {val}')
# protect the entry point
if__name__=='__main__':
# create the shared semaphore
semaphore=Semaphore(2)
# create threads
threads= [Thread(target=task,
args=(semaphore, i)) foriinrange(10)]
# start new threads
forthreadinthreads:
thread.start()
# wait for new threads to finish
forthreadinthreads:
thread.join()