python - 如何在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
的实例上工作,因此一个实例的食物不会被另一个实例改变。
几个问题:
这两个线程都将打印到同一个屏幕。如果您希望 p1 线程在 p2 线程请求输入时暂停打印,您可以尝试使用一个简单的标志在两个线程之间传递信息。
另外,input
如果不输入值,in p2 线程会阻塞,因此即使食物降到 0 以下,如果没有输入值,程序也不会正常退出。
推荐阅读
- typescript - 键入对象属性装饰器
- ros - 如何将 SVG 图像添加到 Gazebo?
- java - java中用户输入的问题
- php - 查看哪个表影响了另一个表 SQL-Server
- python-3.x - numpy ifft 输出的功率比原始信号大得多
- java - 如何在 Android 中检查手机身份验证用户?
- python - 如何在 C 回调中使用 Pybind11 访问 Python 对象?
- python - Python Selenium - AttributeError:“WebElement”对象没有属性“send_Keys”
- php - 在 ApiWrapper.php 第 187 行:无法连接,请检查您的 Algolia 应用程序 ID
- python - 如何在 selenium python 中单击列表的特定类别元素