首页 > 解决方案 > 如何在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()

所以基本上我找不到一种方法来接受输入并保持并行减少食物直到它死去。

标签: pythonpython-3.xparallel-processingmultiprocessingpython-multiprocessing

解决方案


您应该使用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 以下,如果没有输入值,程序也不会正常退出。


推荐阅读