【发布时间】:2014-11-16 20:13:23
【问题描述】:
我正在用 python 编写一个简单的客户端-服务器程序。在客户端程序中,我创建了两个线程(使用 Python 的线程模块),一个用于接收,一个用于发送。接收线程不断地从服务器端接收字符串;而发送线程持续监听用户输入(使用 raw_input())并将其发送到服务器端。两个线程使用 Queue 进行通信(这是本机同步的,LIKE!)。
基本逻辑如下:
接收线程:
global queue = Queue.Queue(0)
def run(self):
while 1:
receive a string from the server side
if the string is QUIT signal:
sys.exit()
else:
put it into the global queue
发送线程:
def run(self):
while 1:
str = raw_input()
send str to the server side
fetch an element from the global queue
deal with the element
如您所见,在接收线程中,我有一个 if 条件来测试服务器是否向客户端发送了“QUIT 信号”。如果有,那么我希望整个程序停止。
这里的问题是,在大部分时间里,发送线程被“raw_input()”阻塞并等待用户输入。当它被阻塞时,从另一个线程(接收线程)调用“sys.exit()”不会立即终止发送线程。发送线程必须等待用户输入内容并按下回车按钮。
有人能启发我如何解决这个问题吗?我不介意使用“raw_input()”的替代品。其实我什至不介意改变整个结构。
-------------编辑-------------
我在 linux 机器上运行它,我的 Python 版本是 2.7.5
【问题讨论】:
-
你是用windows还是linux?
-
应该得到一个“仁慈的简短代码”徽章。
标签: python multithreading