在多线程程序中,如果不适当地使用标准输入(stdin),可能会导致多个线程尝试读取输入,从而引发竞争条件或阻塞程序。为了解决这个问题,可以使用以下方法:
import threading
import sys
# 创建一个锁对象
input_lock = threading.Lock()
def read_input():
with input_lock:
# 使用锁保护标准输入
user_input = input("Enter something: ")
print("You entered:", user_input)
# 创建多个线程读取输入
threads = []
for _ in range(5):
t = threading.Thread(target=read_input)
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
import threading
import sys
import queue
# 创建一个队列对象
input_queue = queue.Queue()
def read_input():
while True:
user_input = input("Enter something (or 'exit' to quit): ")
if user_input == 'exit':
break
input_queue.put(user_input)
def process_input():
while True:
user_input = input_queue.get()
if user_input == 'exit':
break
print("You entered:", user_input)
# 创建读取输入的线程
input_thread = threading.Thread(target=read_input)
input_thread.start()
# 创建处理输入的线程
process_thread = threading.Thread(target=process_input)
process_thread.start()
# 等待读取输入的线程结束
input_thread.join()
# 等待处理输入的线程结束
process_thread.join()
这些方法都可以确保多线程程序中的标准输入不会引发竞争条件或阻塞问题。使用锁或队列可以有效地控制对标准输入的访问,使多个线程可以安全地读取输入。