Skip to main content

LeetCode Solution, Medium, 1115. Print FooBar Alternately

交替印出 FooBar

Published Markdown
Part of seriesLeetCode Solution

1115. Print FooBar Alternately

題目敘述

Suppose you are given the following code:

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");
    }
  }
}

The same instance of FooBar will be passed to two different threads:

  • thread A will call foo(), while
  • thread B will call bar().

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

Constraints:

  • 1 <= n <= 1000

題目翻譯

題目使用 n 表示要執行多少次,每一次執行都依序執行 foo 和 bar。

解法解析

使用 for-loop 跑 n 次,然後使用 acquire 把程式綁住,等待 release 之後才去執行 print 的操作。

程式範例

Python
from threading import Lock


class FooBar:
    def __init__(self, n):
        self.n = n
        self.foolock = Lock()
        self.barlock = Lock()

    def foo(self, printFoo: 'Callable[[], None]') -> None:
        self.barlock.acquire()
        for i in range(self.n):
            self.foolock.acquire()
            # printFoo() outputs "foo". Do not change or remove this line.
            printFoo()
            self.barlock.release()

    def bar(self, printBar: 'Callable[[], None]') -> None:

        for i in range(self.n):
            self.barlock.acquire()
            # printBar() outputs "bar". Do not change or remove this line.
            printBar()
            self.foolock.release()

About the author

  • I am not a programmer just a leaner. Writing JavaScript, Python, and Go and doing something on Kubernetes.

No comments yet. Be the first to comment.

LeetCode Solution

Part 1 of 50

A collection of leetcode solustion

More from this blog