模拟 shell 的多线程程序
Multithreaded program that simulates a shell
我正在尝试制作一个 Python 程序,它与 shell 非常相似:主要是等待用户输入,偶尔会显示来自另一个线程的消息。
考虑到这一点,我编写了以下示例代码:
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 在调用函数 之前计算参数。因此,行:
thread1 = threading.Thread(printSomething())
实际上等同于:
_temp = printSomething()
thread1 = threading.Thread(_temp)
现在可能更清楚发生了什么 - 在 printSomething
中永无休止的 while
循环开始之前,Thread
从未创建,更不用说 start
ed 了。如果您切换了创建顺序,您会看到另一个循环。
相反,根据 the documentation,您需要使用 target
参数来设置
the callable object to be invoked by the run()
method
例如:
thread1 = threading.Thread(target=printSomething)
请注意 printSomething
后没有括号 - 您还不想调用它。
我正在尝试制作一个 Python 程序,它与 shell 非常相似:主要是等待用户输入,偶尔会显示来自另一个线程的消息。
考虑到这一点,我编写了以下示例代码:
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 在调用函数 之前计算参数。因此,行:
thread1 = threading.Thread(printSomething())
实际上等同于:
_temp = printSomething()
thread1 = threading.Thread(_temp)
现在可能更清楚发生了什么 - 在 printSomething
中永无休止的 while
循环开始之前,Thread
从未创建,更不用说 start
ed 了。如果您切换了创建顺序,您会看到另一个循环。
相反,根据 the documentation,您需要使用 target
参数来设置
the callable object to be invoked by the
run()
method
例如:
thread1 = threading.Thread(target=printSomething)
请注意 printSomething
后没有括号 - 您还不想调用它。