-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmulti-threaded-fizzbuzz.py
103 lines (83 loc) · 2.5 KB
/
multi-threaded-fizzbuzz.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import threading
def printFizz():
print("Fizz")
def printBuzz():
print("Buzz")
def printFizzBuzz():
print("FizzBuzz")
def printNumber(i):
print(i)
class MultithreadedFizzBuzz:
def __init__(self, n):
self.__n = n
self.__curr = 0
self.__cv = threading.Condition()
# printFizz() outputs "fizz"
def fizz(self, printFizz):
"""
:type printFizz: method
:rtype: void
"""
for i in range(1, self.__n + 1):
with self.__cv:
while self.__curr % 4 != 0:
self.__cv.wait()
self.__curr += 1
if i % 3 == 0 and i % 5 != 0:
printFizz()
self.__cv.notify_all()
# printBuzz() outputs "buzz"
def buzz(self, printBuzz):
"""
:type printBuzz: method
:rtype: void
"""
for i in range(1, self.__n + 1):
with self.__cv:
while self.__curr % 4 != 1:
self.__cv.wait()
self.__curr += 1
if i % 3 != 0 and i % 5 == 0:
printBuzz()
self.__cv.notify_all()
# printFizzBuzz() outputs "fizzbuzz"
def fizzbuzz(self, printFizzBuzz):
"""
:type printFizzBuzz: method
:rtype: void
"""
for i in range(1, self.__n + 1):
with self.__cv:
while self.__curr % 4 != 2:
self.__cv.wait()
self.__curr += 1
if i % 3 == 0 and i % 5 == 0:
printFizzBuzz()
self.__cv.notify_all()
# printNumber(x) outputs "x", where x is an integer.
def number(self, printNumber):
"""
:type printNumber: method
:rtype: void
"""
for i in range(1, self.__n + 1):
with self.__cv:
while self.__curr % 4 != 3:
self.__cv.wait()
self.__curr += 1
if i % 3 != 0 and i % 5 != 0:
printNumber(i)
self.__cv.notify_all()
fb = MultithreadedFizzBuzz(100)
thread1 = threading.Thread(target=fb.fizz, args=(printFizz,))
thread2 = threading.Thread(target=fb.buzz, args=(printBuzz,))
thread3 = threading.Thread(target=fb.fizzbuzz, args=(printFizzBuzz,))
thread4 = threading.Thread(target=fb.number, args=(printNumber,))
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread1.join()
thread2.join()
thread3.join()
thread4.join()