当前位置: 首页 > news >正文

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

Modify the given program to output "foobar" n times.

 

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

The requirement:

  • Two threads:
    • Thread A calls foo()
    • Thread B calls bar()
  • Output must be:
 
foobarfoobarfoobar...
 

The key problem is: how do we make one thread wait until it is its turn?


Solution 1: Use Semaphore (Recommended)

Use two semaphores:

  • foo_sem: controls when foo() can run
  • bar_sem: controls when bar() can run

Initial state:

 
foo_sem = 1   # foo can run first
bar_sem = 0   # bar must wait
 

Flow:

 
foo thread:print fooallow barbar thread:wait for permissionprint barallow foo
 

Python Implementation

 
from threading import Semaphoreclass FooBar:def __init__(self, n: int):self.n = nself.foo_sem = Semaphore(1)self.bar_sem = Semaphore(0)def foo(self, printFoo) -> None:for _ in range(self.n):self.foo_sem.acquire()printFoo()self.bar_sem.release()def bar(self, printBar) -> None:for _ in range(self.n):self.bar_sem.acquire()printBar()self.foo_sem.release()
 

Execution example

Initial:

 
foo_sem = 1
bar_sem = 0
 

First iteration

Foo thread:

 
acquire foo_sem↓
print foo↓
release bar_sem
 

State:

 
foo_sem = 0
bar_sem = 1
 

Bar thread:

 
acquire bar_sem↓
print bar↓
release foo_sem
 

State:

 
foo_sem = 1
bar_sem = 0
 

Repeat.

Output:

 
foo
bar
foo
bar
foo
bar
 

Solution 2: Use Condition

You can also solve it using Condition.

Maintain a shared variable:

 
turn = "foo"
 

Foo waits until:

 
turn == "foo"
 

Bar waits until:

 
turn == "bar"
 

Python Implementation

 
from threading import Conditionclass FooBar:def __init__(self, n: int):self.n = nself.condition = Condition()self.foo_turn = Truedef foo(self, printFoo) -> None:for _ in range(self.n):with self.condition:while not self.foo_turn:self.condition.wait()printFoo()self.foo_turn = Falseself.condition.notify()def bar(self, printBar) -> None:for _ in range(self.n):with self.condition:while self.foo_turn:self.condition.wait()printBar()self.foo_turn = Trueself.condition.notify()
 

Semaphore vs Condition here

Both work, but they model the problem differently.

Semaphore solution

You are saying:

"Foo has a permit to print. After printing, give the permit to Bar."

The semaphore itself stores the state.

 
foo_sem = 1
bar_sem = 0
 

Very natural for alternating execution.


Condition solution

You are saying:

"Threads should wait until the shared state foo_turn changes."

The state is external:

 
foo_turn = True
 

The condition only wakes threads.

http://www.jsqmd.com/news/1198579/

相关文章:

  • 格拉苏蒂中国官方专柜客服电话权威信息声明(2026年7月最新) - 亨得利官方服务中心
  • 保定工地基坑排水清淤、管廊排水、河道池塘清淤、泵站污水池清底、泥浆清运、污水转运、蓄水池清淤哪家好?禹通管道疏通京津冀地区24小时工程服务与收费标准详解 - 实用旅游攻略分享
  • 2026年7月最新海口天梭官方售后客户服务电话及线下网点地址 - 天梭服务中心
  • 去贵州玩跟团还是自由行?哪家旅行社靠谱?贵州卓途艾旅行社资质、服务与真实口碑解析 - 实用旅游攻略分享
  • 宝玑中国官方售后服务中心|服务热线及完整地址权威信息通告(2026年7月最新) - 亨得利钟表维修中心
  • 百达翡丽官方更换表蒙价格查询|网点地址与24小时售后热线权威信息公告(2026年7月最新) - 百达翡丽服务中心
  • 真力时官网服务售后维修保养服务指南权威公示(2026年7月最新) - 亨得利钟表维修中心
  • 2026年7月最新徐州百达翡丽官方售后服务网点地址及客服电话一览 - 百达翡丽官方售后中心
  • 2026年7月最新——北海靠谱防水公司推荐丨按4项标准实测后的达标清单 - 捷修防水
  • 2026年7月最新广州格拉苏蒂官方售后维修服务网点地址与客服电话 - 亨得利钟表维修中心
  • 2026 年更新:商丘靠谱的矿用撬毛台车供货厂家怎么联系,别再瞎搬了!揭秘高效采矿的秘密工具 - 实业推荐官【官方】
  • 格拉苏蒂中国官方售后服务中心|服务热线及全部网点地址权威信息公告(2026年7月最新) - 亨得利钟表维修中心
  • 泰格豪雅中国官方售后服务中心|最新电话和网点地址权威信息通告(2026年7月更新) - 亨得利官方服务中心
  • 2026年7月亲身到店探访海口亨得利官方名表服务中心|详细网点地址及服务电话 - 亨得利官方
  • 浪琴中国官方售后服务中心|全新热线和维修地址权威信息公示(2026年7月更新) - 浪琴服务中心
  • 2026年最新教程:视频里的声音怎么单独保存亲测有效 - 图片处理研究员
  • 2026年7月最新——云浮防水补漏哪家正规?从检测报价质保合同4项看 - 家居避坑指南
  • 萧邦中国官方售后服务中心|服务热线及官方维修地址权威信息通知(2026年7月更新) - 萧邦中国官方服务中心
  • 2026亲测有效教程:图片大小必须小于300K怎么弄 - 图片处理研究员
  • 保定工地基坑排水清淤、管廊排水、河道池塘清淤、泵站污水池清底、蓄水池清淤——京津冀地区工程排水清淤哪家能做? - 实用旅游攻略分享
  • 2026年7月最新亨得利官方服务项目及价格查询|服务热线及完整地址权威信息公告 - 亨得利官方博客
  • 2026年7月最新——乐山防水补漏哪家好?4项标准对照3家后结论自己看 - 捷修防水
  • 2026 年更新:霸州评价高的无土绿化喷播植草批发厂家哪家权威,别再买土了!揭秘无土绿化喷播植草的惊人效率 - 行业推荐官【认证】
  • 2026年最新教程:PDF课件怎么改成PPT 亲测好用的免费方法 - 图片处理研究员
  • 2026年7月最新——吕梁防水补漏哪家靠谱?按4条标准筛过后的避坑清单 - 家居避坑指南
  • 2026年7月最新大连萧邦官方售后客户服务热线与维修网点地址汇总 - 萧邦中国官方服务中心
  • 亨得利官方钟表服务中心|官方电话和维修地址权威信息公告(2026年7月更新) - 亨得利官方
  • 2026年7月最新——克拉玛依防水补漏哪家靠谱?按4条标准筛过后的避坑清单 - 家居避坑指南
  • 真力时中国官方售后服务中心|服务热线及官方维修地址权威信息声明(2026年7月最新) - 亨得利官方服务中心
  • 2026年7月最新——南充防水补漏哪家正规?从检测报价质保合同4项看 - 家居避坑指南