如何在 python 中获取用户输入和 运行 另一个并行连续计算,同时我们提供输入

how to take input from a user and run another continuous calculation in parallel while we feed the input, in 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 线程请求输入时暂停打印,你可以尝试使用一个简单的标志来在两个线程之间传递信息。

另外p2线程input如果不输入值会阻塞,所以即使food降到0以下也不输入值程序也不会正常退出