您当前的位置: 首页 >  ar

LeetCode 多线程 1115. 交替打印FooBar

发布时间:2021-07-15 09:29:40 ,浏览量:0

1115. 交替打印FooBar

Ideas

交替锁的设计,两把锁,foo执行的时候把foo lock acquire,print完了只有把bar lock release,这样foo就得等着,然后bar执行的时候把bar lock acquire,print完了之后把foo lock release,这样就能交替打印foo和bar了。

Code Python
from threading import Lock class FooBar: def __init__(self, n): self.n = n
        self.print_foo = Lock() self.print_bar = Lock() self.print_bar.acquire() def foo(self, printFoo: 'Callable[[], None]') -> None: for i in range(self.n): self.print_foo.acquire() # printFoo() outputs "foo". Do not change or remove this line. printFoo() self.print_bar.release() def bar(self, printBar: 'Callable[[], None]') -> None: for i in range(self.n): self.print_bar.acquire() # printBar() outputs "bar". Do not change or remove this line. printBar() self.print_foo.release() 
关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    109273博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.1973s