交替打印FooBar - 使用两个事件实现(Event)

交替打印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” 将被输出两次。


分析

python的threading试下了事件对象Event,该对象拥有三个主要方法:set() clear() wait()

进程或者线程同步的概念中有相似的叙述,一个进程(或线程)的执行依赖于另一个进程(或线程)的执行状态。

使用两个Event对象,实现使一个线程事件的触发依赖于另一个线程事件的触发。

解法

from threading import Event
class FooBar:
    def __init__(self, n):
        self.n = n
        self.event_bar = Event()
        self.event_foo = Event()
        self.event_foo.set()

    def foo(self, printFoo: 'Callable[[], None]') -> None:
        
        for i in range(self.n):
            self.event_foo.wait()
            # printFoo() outputs "foo". Do not change or remove this line.
            printFoo()
            # 阻塞foo
            self.event_foo.clear()
            # 唤醒bar
            self.event_bar.set()
            
            


    def bar(self, printBar: 'Callable[[], None]') -> None:
        
        for i in range(self.n):
            self.event_bar.wait()
            # printBar() outputs "bar". Do not change or remove this line.
            printBar()
            # 阻塞bar
            self.event_bar.clear()
            # 唤醒foo
            self.event_foo.set()

题目来源于leetcode

猜你喜欢

转载自blog.csdn.net/qq_39378657/article/details/109574510