首页 > 解决方案 > 来自 if 语句的多处理

问题描述

我有一个关于线程和/或多处理的快速问题。是否有任何简单的杀死线程的方法,是否可以从 if 语句启动进程。

我对编码很陌生,不知道编码中的大术语,所以我很难理解其他一些答案。

from multiprocessing import Process
done = False

def a():
    print('a')

p = Process(target = a)

while not done:
    userInput = input('')
    if userInput == '1':
        p.start()
    if userInput == '2':
        done = True
import threading
done = False

def a():
    print('a')

p = threading.Thread(target = a)

while not done:
    userInput = input('')
    if userInput == '1':
        p.start()
    if userInput == '2':
        done = True

我希望当我输入 1 时它会输出 a 但它什么也没做。当我再次尝试时,它给了我错误,AssertionError: cannot start a process两次。我能做些什么来解决这个问题。我知道线程工作一次,但如果我想第二次运行,我必须添加什么。

标签: python-3.x

解决方案


推荐阅读