1115. Print FooBar Alternately
- Print FooBar Alternately python solution
题目描述
解析
多线程操作的题目,思路比较简单,使用Lock
在Lock.acquire() Lock.release()之间的程序,是不会被其他线程所调用的。
// An highlighted block
from threading import Lock
class FooBar(object):
def __init__(self, n):
self.n = n
self.f = Lock()
self.b = Lock()
self.b.acquire()
def foo(self, printFoo):
"""
:type printFoo: method
:rtype: void
"""
for i in range(self.n):
self.f.acquire()
# printFoo() outputs "foo". Do not change or remove this line.
printFoo()
self.b.release()
def bar(self, printBar):
"""
:type printBar: method
:rtype: void
"""
for i in range(self.n):
self.b.acquire()
# printBar() outputs "bar". Do not change or remove this line.
printBar()
self.f.release()
Reference
https://leetcode.com/problems/print-foobar-alternately/discuss/336629/5-Python-threading-solutions-(Barrier-Event-Condition-Lock-Semaphore)-with-explanation