Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf05596a

Browse files
1115 Print FooBar Alternately.py
1 parenta80e97f commitf05596a

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎1115 Print FooBar Alternately.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/python3
2+
"""
3+
Suppose you are given the following code:
4+
5+
class FooBar {
6+
public void foo() {
7+
for (int i = 0; i < n; i++) {
8+
print("foo");
9+
}
10+
}
11+
12+
public void bar() {
13+
for (int i = 0; i < n; i++) {
14+
print("bar");
15+
}
16+
}
17+
}
18+
The same instance of FooBar will be passed to two different threads. Thread A
19+
will call foo() while thread B will call bar(). Modify the given program to
20+
output "foobar" n times.
21+
22+
23+
24+
Example 1:
25+
26+
Input: n = 1
27+
Output: "foobar"
28+
Explanation: There are two threads being fired asynchronously. One of them calls
29+
foo(), while the other calls bar(). "foobar" is being output 1 time.
30+
Example 2:
31+
32+
Input: n = 2
33+
Output: "foobarfoobar"
34+
Explanation: "foobar" is being output 2 times.
35+
"""
36+
fromthreadingimportLock
37+
fromtypingimportCallable
38+
39+
40+
classFooBar:
41+
def__init__(self,n):
42+
self.n=n
43+
self.locks= [Lock(),Lock()]
44+
self.locks[1].acquire()
45+
46+
47+
deffoo(self,printFoo:Callable[[],None])->None:
48+
foriinrange(self.n):
49+
self.locks[0].acquire()
50+
# printFoo() outputs "foo". Do not change or remove this line.
51+
printFoo()
52+
self.locks[1].release()
53+
54+
55+
defbar(self,printBar:Callable[[],None])->None:
56+
foriinrange(self.n):
57+
self.locks[1].acquire()
58+
# printBar() outputs "bar". Do not change or remove this line.
59+
printBar()
60+
self.locks[0].release()

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp