【问题标题】:Multithreaded program that simulates a shell模拟外壳的多线程程序
【发布时间】:2015-03-19 16:35:39
【问题描述】:

我正在尝试制作一个很像 shell 的 Python 程序:主要等待用户输入,偶尔显示来自另一个线程的消息。

考虑到这一点,我制作了以下示例代码:

import threading
import time

def printSomething(something="hi"):
    while True:
        print(something)
        time.sleep(2)

def takeAndPrint():
    while True:
        usr = input("Enter anything: ")
        print(usr)

thread1 = threading.Thread(printSomething())
thread2 = threading.Thread(takeAndPrint())

thread1.start()
thread2.start()

我预期会发生什么

提示用户输入;有时这会导致他们的消息被输出,其他时候printSomething 消息首先打印。

Enter anything:
hi
Enter anything: hello
hello
Enter anything: 
hi

实际发生了什么

似乎只有printSomething 运行:

hi
hi
hi

我需要怎么做才能持续提示用户输入,同时根据需要打印来自其他线程的消息?

【问题讨论】:

    标签: python multithreading python-3.x python-multiprocessing


    【解决方案1】:

    请注意,Python 在调用函数之前会评估参数。因此,行:

    thread1 = threading.Thread(printSomething())
    

    实际上等价于:

    _temp = printSomething()
    thread1 = threading.Thread(_temp)
    

    现在可能更清楚发生了什么 - 在printSomething 中永无止境的while 循环开始之前,从未创建过Thread,更不用说started。如果您切换了创建顺序,您会看到另一个循环。

    相反,根据the documentation,您需要使用target 参数来设置

    run() 方法调用的可调用对象

    例如:

     thread1 = threading.Thread(target=printSomething)
    

    注意printSomething 后面没有括号 - 你还不想调用它。

    【讨论】:

    • 好吧...比我的回答好得多:P ....虽然也许您应该将剧透保存为用户的学习练习:P(+1)
    • 感谢您的帮助。如果我首先启动 thread2 而不是 thread1 它仍然会执行 his 的列表。
    • @fdsa - 同样,start 永远无法到达。您start他们的顺序无关紧要,但您分配他们的顺序无关紧要。请更仔细地重新阅读我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    相关资源
    最近更新 更多