Print FooBar alternately-using two events to achieve (Event)

Print FooBar alternately

We provide a class:

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

Two different threads will share a FooBar instance. One thread will call the foo() method, and the other thread will call the bar() method.

Please design and modify the program to ensure that "foobar" is output n times.

Example 1:
Input: n = 1
Output: "foobar"
Explanation: There are two threads started asynchronously. One calls the foo() method, and the other calls the bar() method. "foobar" will be output once.

Example 2:
Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" will be output twice.


analysis

Python threading tried the event object Event, which has three main methods:set() clear() wait()

There is a similar description in the concept of process or thread synchronization. The execution of one process (or thread) depends on the execution state of another process (or thread).

Using two Eventobjects, the triggering of one thread event depends on the triggering of another thread event.

solution

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()

The topic comes from leetcode

Guess you like

Origin blog.csdn.net/qq_39378657/article/details/109574510