2019-04-24

基于生产者与消费者的多线程Python实现

生产者生产,消费者消费,都是针对二者共同的钱包,生产者生产的钱放入钱包,消费者是对钱包消费,所以需要对钱包进行上锁,其中的钱只能供一个角色进行操作,不存在生产与消费同时进行


gMoney=1000

glock=threading.Lock()

gtime=0

class produce(threading.Thread):

    def run(self):

        global gMoney

        global gtime

        while True:

            money=random.randint(100,1000)

            glock.acquire()

             if gtime>=10:

                glock.release()

                break

            gMoney+=money

            print("%s生产了%d元钱,剩余%d" %(threading.current_thread(),money,gMoney))

            gtime+=1

            glock.release()

            time.sleep(0.5)

class consummer(threading.Thread):

    def run(self):

        global gMoney

        while True:

            money=random.randint(100,1000)

            glock.acquire()

            if gMoney >=money:

                gMoney-=money

                print("%s消费者消费了%d元钱,剩余%d元钱" %(threading.current_thread(),money,gMoney))

             else:

                if gtime>=10:

                    glock.release()

                    break

                  print("%s消费者想消费%d元,此时余额%d元,不足,请等待"%(threading.current_thread(),money,gMoney))

            glock.release()

            time.sleep(0.5)

def main():

    for xin range(7):

    t=consummer(name="消费者%d" %x)

    t.start()

    for xin range(5):

    t=produce(name="生产者%d" %x)

    t.start()

if __name__=="__main__":

    main()

你可能感兴趣的:(2019-04-24)