Python多线程小练习

最近学习Python的多线程,遇到一个小题目,练习练习QwQ,题目如下:

有两个缓冲区A和B,A的容量为6,B的容量为5,有3个操作Put,Move,Get,分别表示放一个东西到A中,将一个东西从A搬到B,从B中取出一个东西。

实现代码如下:

import threading
import time

Aempty = threading.Semaphore(6)
Afull  = threading.Semaphore(0)
Amutex = threading.Semaphore(1)
Bempty = threading.Semaphore(5)
Bfull  = threading.Semaphore(0)
Bmutex = threading.Semaphore(1)

def Put():
    for i in range(200):
        Aempty.acquire()
        Amutex.acquire()
        print("Put an apple into A")
        Amutex.release()
        Afull.release()

def Move():
    for i in range(200):
        Afull.acquire()
        Bempty.acquire()
        Amutex.acquire()
        Bmutex.acquire()
        print("Move an apple from A to B")
        time.sleep(0.1)
        Amutex.release()
        Bmutex.release()
        Aempty.release()
        Bfull.release()

def Get():
    for i in range(200):
        Bfull.acquire()
        Bmutex.acquire()
        print("Get an apple from B")
        time.sleep(0.1)
        Bmutex.release()
        Bempty.release()

t1 = threading.Thread(target = Put)
t2 = threading.Thread(target = Move)
t3 = threading.Thread(target = Get)

t1.start()
t2.start()
t3.start()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值