-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore.py
69 lines (51 loc) · 1.41 KB
/
semaphore.py
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
65
import threading
import random
import time
class User(threading.Thread):
running = True
def __init__(self, username, right, left):
threading.Thread.__init__(self)
self.username = username
self.left = left
self.right = right
def run(self):
while self.running:
time.sleep(random.uniform(1, 5))
print("user %s : READY TO RUN " % self.username)
self.use()
def use(self):
ileft, iright = self.left, self.right
while self.running:
ileft.acquire()
locked = iright.acquire(False)
if locked:
break
ileft.release()
else:
return
self.using()
ileft.release()
iright.release()
def using(self):
print('user %s : START' % self.username)
time.sleep(random.uniform(1, 7))
print('user %s : FINISH' % self.username)
def main():
usb = threading.Semaphore()
network = threading.Semaphore()
graphic = threading.Semaphore()
memory = threading.Semaphore()
a = User('A', network, graphic)
b = User('B', usb, memory)
c = User('C', memory, graphic)
d = User('D', network, usb)
User.running = True
a.start()
b.start()
c.start()
d.start()
time.sleep(15)
print("end of process...")
User.running = False
if __name__ == "__main__":
main()