-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint-foobar-alternately.py
More file actions
52 lines (42 loc) · 1.49 KB
/
print-foobar-alternately.py
File metadata and controls
52 lines (42 loc) · 1.49 KB
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
""" Using threading.Event """
from threading import Event
class FooBar:
def __init__(self, n):
self.n = n
self.foo_lock = Event()
self.bar_lock = Event()
self.foo_lock.set()
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
self.foo_lock.wait()
# printFoo() outputs "foo". Do not change or remove this line.
printFoo()
self.foo_lock.clear()
self.bar_lock.set()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
self.bar_lock.wait()
# printBar() outputs "bar". Do not change or remove this line.
printBar()
self.bar_lock.clear()
self.foo_lock.set()
""" Using threading.Lock """
from threading import Lock
class FooBar:
def __init__(self, n):
self.n = n
self.foo_lock = Lock()
self.bar_lock = Lock()
self.bar_lock.acquire()
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
self.foo_lock.acquire()
# printFoo() outputs "foo". Do not change or remove this line.
printFoo()
self.bar_lock.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
self.bar_lock.acquire()
# printBar() outputs "bar". Do not change or remove this line.
printBar()
self.foo_lock.release()