gpt4 book ai didi

python - 如何在Python中的线程中增加类字段?

转载 作者:行者123 更新时间:2023-12-01 04:13:48 26 4
gpt4 key购买 nike

我正在尝试实现一个小花园示例。Garden 是一个具有 grow() 的类功能,检查每秒供应的水量。当水量超过某个阈值时,花园就会开出一些花。

这是我的第一次尝试:

花园课

import time

class Garden:
def __init__(self):
self.water = 0
print("Garden built!")

def grow(self):
while self.water < 50:
print("Water supplied: {0}".format(self.water))
time.sleep(1)
print("Produced 5 flowers!")

ma​​in.py

import time
from garden import Garden
from threading import Thread
from queue import Queue

def main():
que = Queue()
garden = Garden()
thr = Thread(target=garden.grow).start()
que_garden = que.get()
water(que_garden, 20)
time.sleep(5)
water(que_garden, 30)
thr.join()

def water(garden, amount):
garden.water += amount
print("Watered with {0}!".format(amount))

当我运行main.py时我得到以下输入:

Garden built!
Water supplied: 0
Water supplied: 0
Water supplied: 0
Water supplied: 0
Water supplied: 0

所以,grow()不断地接到电话,但从未接通water(que_garden, 20)线。我预料到了一次thr = Thread(target=garden.grow).start()被调用时它不会被锁定,直到 grow()完成但继续下一行。我在这里缺少什么?

最佳答案

这个:

que_garden = que.get()

阻塞,直到队列中有东西为止。但任何地方都没有 que_garden.put()

这无需队列即可工作:

import time
from garden import Garden
from threading import Thread

def main():
garden = Garden()
thr = Thread(target=garden.grow)
thr.start()
water(garden, 20)
time.sleep(5)
water(garden, 30)
time.sleep(5)
water(garden, 10)
thr.join()

def water(garden, amount):
garden.water += amount
print("Watered with {0}!".format(amount))

main()

输出:

Garden built!
Water supplied: 0
Watered with 20!
Water supplied: 20
Water supplied: 20
Water supplied: 20
Water supplied: 20
Watered with 30!
Produced 5 flowers!
Watered with 10!

关于python - 如何在Python中的线程中增加类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com