如何解决如何从用户那里获取输入并在我们使用python输入输入的同时并行运行另一个连续计算
这是我的代码,
import multiprocessing,time
class titan:
food = 500
def foo(self):
titan.food = titan.food - 10
print(titan.food,'food left')
time.sleep(.5)
def ask(self):
if titan.food < 400:
x = input("give food?")
if x == 'yes':
titan.food = titan.food + 100
print('food refilled!----->>>>',titan.food)
elif x == 'no':
print('u making me dead')
else:
print('enter valid input')
elif titan.food == 0:
print("My time has come !!! + ")
break
a = titan()
p1 = multiprocessing.Process(target=a.foo)
p2 = multiprocessing.Process(target=a.ask)
p1.start()
p2.start()
p1.join()
p2.join()
所以基本上我无法找到一种方法来吸收食物并持续减少食物直到死亡。
解决方法
您应该使用threading
而不是multiprocessing
。
这是编辑
import time
from threading import Thread
class titan:
food = 500
def foo(self):
# maybe you should do a loop here?
while True:
# normally,you should alter instance property rather than class property.
# so it's better to update self.food,rather than titan.food .
self.food = self.food - 10
print(self.food,'food left')
time.sleep(.5)
# maybe you want to exit if food is <0?
if self.food < 0:
break
def ask(self):
# maybe you also want a loop here?
while True:
if self.food < 400:
x = input("give food?")
if x == 'yes':
self.food = self.food + 100
print('food refilled!----->>>>',self.food)
elif x == 'no':
print('u making me dead')
else:
print('enter valid input')
# shouldn't use elif here,because if food < 0,# it will also satisfy food<400,# thus the elif block will never be executed.
if self.food < 0:
print("My time has come !!! + ")
break
a = titan()
p1 = Thread(target=a.foo)
p2 = Thread(target=a.ask)
p1.start()
p2.start()
p1.join()
p2.join()
在您的情况下,threading
有效但multiprocessing
不起作用的原因是,在threading
模型中,两个线程可以修改相同的实例值,而在multiprocessing
中,另一个进程分叉出来,并在另一个过程中创建另一个titan
实例。这两个进程将在不同的titan
实例上工作,因此一个实例的食物不会被另一个实例更改。
一些问题:
这两个线程都将打印到同一屏幕上。如果希望在p2线程请求输入时暂停p1线程的打印,则可以尝试使用简单的标志在两个线程之间传递信息。
此外,如果您不输入值,则p2线程中的input
会阻塞,因此,即使在食物跌落到0以下之后,如果没有输入任何值,程序也不会正常退出。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。