1115. 交替打印FooBar
我们提供一个类:
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");
}
}
}
两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。
请设计修改程序,以确保 "foobar" 被输出 n 次。
示例 1:
输入: n = 1
输出: "foobar"
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。
示例 2:
输入: n = 2
输出: "foobarfoobar"
解释: "foobar" 将被输出两次。
python3解法(锁):
class FooBar:
def __init__(self, n):
self.n = n
self.foolock = threading.Lock()
self.barlock = threading.Lock()
self.barlock.acquire()
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
# printFoo() outputs "foo". Do not change or remove this line.
self.foolock.acquire()
printFoo()
self.barlock.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
# printBar() outputs "bar". Do not change or remove this line.
self.barlock.acquire()
printBar()
self.foolock.release()
python3解法(信号量):
import threading
# Semaphore对象内部管理一个计数器,该计数器由每个acquire()调用递减,并由每个release()调用递增。
# 计数器永远不会低于零,当acquire()发现计数器为零时,线程阻塞,等待其他线程调用release()
# 本质就是生产者与消费者问题,foo是生产者,bar是消费者,要先生产才能被消费,且商品缓冲区上限为1
foo = threading.Semaphore(1)
bar = threading.Semaphore(0)
class FooBar:
def __init__(self, n):
self.n = n
# self.foolock = threading.Lock()
# self.barlock = threading.Lock()
# self.barlock.acquire()
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
# printFoo() outputs "foo". Do not change or remove this line.
foo.acquire()
printFoo()
bar.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
# printBar() outputs "bar". Do not change or remove this line.
bar.acquire()
printBar()
foo.release()
网友评论