Leetcode 1115. Print FooBar Alternately解题报告(python)

本文介绍了一种使用Python的Lock机制实现多线程交替打印'Foo'和'Bar'的方法。通过创建两个锁,一个用于Foo,一个用于Bar,确保了线程的安全交替执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1115. Print FooBar Alternately

  1. Print FooBar Alternately python solution

题目描述

在这里插入图片描述

解析

多线程操作的题目,思路比较简单,使用Lock
在Lock.acquire() Lock.release()之间的程序,是不会被其他线程所调用的。

// An highlighted block
from threading import Lock
class FooBar(object):
    def __init__(self, n):
        self.n = n
        self.f = Lock()
        self.b = Lock()
        self.b.acquire()
    def foo(self, printFoo):
        """
        :type printFoo: method
        :rtype: void
        """
        for i in range(self.n):
            self.f.acquire()
            # printFoo() outputs "foo". Do not change or remove this line.
            printFoo()
            self.b.release()
    def bar(self, printBar):
        """
        :type printBar: method
        :rtype: void
        """
        for i in range(self.n):
            self.b.acquire()
            # printBar() outputs "bar". Do not change or remove this line.
            printBar()
            self.f.release()    

Reference

https://leetcode.com/problems/print-foobar-alternately/discuss/336629/5-Python-threading-solutions-(Barrier-Event-Condition-Lock-Semaphore)-with-explanation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值