10-2 HNCST - 多线程4 - 线程同步Condition——python

2023-12-31 22:34:10

有一家店铺里有4个销售和2个搬运工,销售负责卖货,搬运工负责从仓库搬货物,已知该店铺的存货有size,当销售或搬运工做完所有商品数量后,他们各自就可以下班。销售可以同时卖货,但只能按照货架顺序每次卖出一件,搬运工一次可以搬满货架,货架容量为5个货物。当货架商品销售完后,搬运工会去仓库搬运货物进行补货,销售此时进行小憩;当货架补满后,销售开始销售商品,搬运工进行休息。

本题要求实现搬运工Porter类和销售Seller类,他们都是线程类。

提示:本题需要使用Condition类来保证销售不会乱卖商品,保证搬运工不会在商品未销售完时搬运货物。

裁判测试程序样例:

from threading import Thread, Condition

# ***************

# 你编写的类将放在这

# ***************


size = int(input())
Porter.size = Seller.size = size
condi = Condition()
shelves = []

for _ in range(2):
    Porter().start()

for _ in range(4):
    Seller().start()


?

输入样例:

在这里给出一组输入。例如:

20

输出样例:

在这里给出相应的输出。例如:

已生产商品: 1 2 3 4 5
已销售商品: 1
已销售商品: 2
已销售商品: 3
已销售商品: 4
已销售商品: 5
已生产商品: 1 2 3 4 5
已销售商品: 1
已销售商品: 2
已销售商品: 3
已销售商品: 4
已销售商品: 5
已生产商品: 1 2 3 4 5
已销售商品: 1
已销售商品: 2
已销售商品: 3
已销售商品: 4
已销售商品: 5
已生产商品: 1 2 3 4 5
已销售商品: 1
已销售商品: 2
已销售商品: 3
已销售商品: 4
已销售商品: 5
class Porter(Thread):
    def run(self):
        global shelves
        condi.acquire()
        while Porter.size > 0:
            if len(shelves) >= 5:
                condi.notify()
                condi.wait()
            else:
                if len(shelves) <= 0:
                    print("已生产商品:",end='')
                shelves.append(6)
                Porter.size -= 1
                if len(shelves) >=5 or Porter.size <= 0:
                    print(f" {len(shelves)}")
                else:
                    print(f" {len(shelves)}",end = '')
        condi.notify()
        condi.release()

class Seller(Thread):
    def run(self):
        global shelves,tps,n
        with condi:
            while len(shelves) > 0 or Seller.size > 0:
                if len(shelves) <= 0:
                    condi.notify()
                    condi.wait()
                else:
                    del shelves[0]
                    Seller.size -= 1
                    if Seller.size == len(shelves) and n == 0:
                        tps = len(shelves) + 1
                        n = 1
                    print(f"已销售商品: {tps - len(shelves)}",end = '')
                    if Seller.size > 0:
                        print()


tps = 5
n = 0

?

文章来源:https://blog.csdn.net/qq_64037242/article/details/135319653
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。