-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathprint_foobar.py
40 lines (33 loc) · 1.15 KB
/
print_foobar.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
Suppose you are given the following code:
class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.
# -----------------------------------------------------------------------------------------------------
Use two locks for the threads to signal to each other when the other should run. bar_lock starts in a locked state because we always want foo to print first.
import threading
class FooBar:
def __init__(self, n):
self.n = n
self.foo_lock = threading.Lock()
self.bar_lock = threading.Lock()
self.bar_lock.acquire()
def foo(self, printFoo):
for i in range(self.n):
self.foo_lock.acquire()
printFoo()
self.bar_lock.release()
def bar(self, printBar):
for i in range(self.n):
self.bar_lock.acquire()
printBar()
self.foo_lock.release()