forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample8.py
More file actions
40 lines (29 loc) · 931 Bytes
/
example8.py
File metadata and controls
40 lines (29 loc) · 931 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
35
36
37
38
39
40
# ch12/example8.py
import threading
import time
class Spouse(threading.Thread):
def __init__(self, name, partner):
threading.Thread.__init__(self)
self.name = name
self.partner = partner
self.hungry = True
def run(self):
while self.hungry:
print('%s is hungry and wants to eat.' % self.name)
if self.partner.hungry:
print('%s is waiting for their partner to eat first...' % self.name)
else:
with fork:
print('%s has stared eating.' % self.name)
time.sleep(5)
print('%s is now full.' % self.name)
self.hungry = False
fork = threading.Lock()
partner1 = Spouse('Wife', None)
partner2 = Spouse('Husband', partner1)
partner1.partner = partner2
partner1.start()
partner2.start()
partner1.join()
partner2.join()
print('Finished.')