当前位置:网站首页>多线程相关:按序打印、交替打印FooBar、交替打印字符串
多线程相关:按序打印、交替打印FooBar、交替打印字符串
2022-08-09 15:04:00 【凤求凰的博客】
一、按序打印

from threading import Lock
class Foo:
def __init__(self):
self.firstJobDone = Lock()
self.secondJobDone = Lock()
self.firstJobDone.acquire()
self.secondJobDone.acquire()
# 要求执行顺序是first、second、third
def first(self, printFirst: 'Callable[[], None]') -> None:
printFirst()
self.firstJobDone.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
with self.firstJobDone: # with语法:自动获取且用完之后自动释放锁
printSecond()
self.secondJobDone.release()
def third(self, printThird: 'Callable[[], None]') -> None:
with self.secondJobDone:
printThird()
二、交替打印FooBar

''' 生产者与消费者模型(信号量解法) acquire(),表示p操作,加1 release(),表示v操作,减1 '''
class FooBar:
def __init__(self, n):
self.n = n
self.p = threading.Semaphore(1)
self.v = threading.Semaphore(0)
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
self.p.acquire()
printFoo()
self.v.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
self.v.acquire()
printBar()
self.p.release()
三、交替打印字符串(不懂)


from threading import Semaphore
class FizzBuzz:
def __init__(self, n: int):
self.n = n
self.sem_fizz = Semaphore(0)
self.sem_buzz = Semaphore(0)
self.sem_fibu = Semaphore(0)
self.sem_num = Semaphore(1)
# printFizz() outputs "fizz"
def fizz(self, printFizz: 'Callable[[], None]') -> None:
for i in range(1, self.n+1):
if i % 3 == 0 and i % 5 != 0:
self.sem_fizz.acquire()
printFizz()
self.sem_num.release()
# printBuzz() outputs "buzz"
def buzz(self, printBuzz: 'Callable[[], None]') -> None:
for i in range(1, self.n+1):
if i % 3 != 0 and i % 5 == 0:
self.sem_buzz.acquire()
printBuzz()
self.sem_num.release()
# printFizzBuzz() outputs "fizzbuzz"
def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:
for i in range(1, self.n+1):
if i % 3 == 0 and i % 5 == 0:
self.sem_fibu.acquire()
printFizzBuzz()
self.sem_num.release()
# printNumber(x) outputs "x", where x is an integer.
def number(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n+1):
self.sem_num.acquire()
if i % 3 == 0 and i % 5 == 0:
self.sem_fibu.release()
elif i % 3 == 0:
self.sem_fizz.release()
elif i % 5 == 0:
self.sem_buzz.release()
else:
printNumber(i)
self.sem_num.release()
边栏推荐
猜你喜欢
随机推荐
websocket协议详解
Monte Carlo simulation
微信小程序学习(二)
Tracert 命令穿越防火墙不显示星号*的方法
在任务管理器中结束任务进程之后电脑直接黑屏了
Ntdsutil 清除无效的辅域控制器DC
FFmpeg源码剖析-通用:ffmpeg_parse_options()
WinServer 2019 组策略删除本地管理员且只允许域用户登陆
ARM基础知识点笔记
properties文件的读取和写入
FPGA--基础语句、计数器、测试仿真语句(个人学习记录2022.7.20)
二维数组的探究
ACL配置
域控同步相关命令
vs2017下配置sqlite3环境
ASCII码表
Unity UI框架思路与实现
Vim practical skills_3. Visual mode and command mode
idea 用不了Ctrl+Shift+F快捷键全局搜索。
新电脑自带win11,开机怎样跳过连网









