Print FooBar alternately-semaphore and lock

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

Semaphore: A mechanism used in multithreading to ensure that two or more key code segments are not called concurrently. A thread must obtain the semaphore before entering a critical code; after executing the critical code, the semaphore must be released. Other threads that have not obtained the semaphore need to wait for the thread occupying the semaphore to release the semaphore.

For this problem, initially set one for consumers 信号量0.
When it 信号量is n, it means that the producer has produced n resources, and the consumer can consume n resources continuously.

According to the requirements of the topic, the goal is to produce one by the producer and consume one by the consumer to achieve the simultaneous effect of production and consumption.

Then add one for the producer at this time , and the consumer controls the release of the lock. When the consumer consumes the producer’s product, release the lock (tell the consumer that I have already digested the one you produced), and then the producer can continue produce.

solution

from threading import Lock, Semaphore
class FooBar:
    def __init__(self, n):
        self.n = n
        # 设置一个信号量,初始时资源为0
        self.s = Semaphore(0)
        # 设置一个锁
        self.lock = Lock()

    def foo(self, printFoo: 'Callable[[], None]') -> None:
        
        for i in range(self.n):
            # 生产者拿锁
            self.lock.acquire()
            # product
            # printFoo() outputs "foo". Do not change or remove this line.
            printFoo()
            # 释放信号量
            self.s.release()
            
            


    def bar(self, printBar: 'Callable[[], None]') -> None:
        
        for i in range(self.n):
            # 获取资源,获取信号量
            self.s.acquire()
            # printBar() outputs "bar". Do not change or remove this line.
            # 消耗
            printBar()
            # 释放锁,消耗完之后再让生产者生产
            self.lock.release()

Guess you like

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