see*_*uch 6 python multithreading
我在python中编写一个简单的客户端 - 服务器程序.在客户端程序中,我创建了两个线程(使用Python的线程模块),一个用于接收,一个用于发送.接收线程从服务器端连续接收字符串; 而发送线程持续监听用户输入(使用raw_input())并将其发送到服务器端.这两个线程使用队列进行通信(本机同步,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
Run Code Online (Sandbox Code Playgroud)
发送帖子:
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
Run Code Online (Sandbox Code Playgroud)
如您所见,在接收线程中,我有一个if条件来测试服务器是否已向客户端发送"QUIT信号".如果有,那么我希望整个程序停止.
这里的问题是,在大多数情况下,发送线程被"raw_input()"阻塞并等待用户输入.当它被阻塞时,从另一个线程(接收线程)调用"sys.exit()"将不会立即终止发送线程.发送线程必须等待用户输入内容并按下回车按钮.
任何人都可以激励我如何解决这个问题吗?我不介意使用"raw_input()"的替代品.其实我甚至不介意改变整个结构.
- - - - - - -编辑 - - - - - - -
我在linux机器上运行它,我的Python版本是2.7.5
您可以将发送线程设置为守护进程:
send_thread = SendThread() # Assuming this inherits from threading.Thread
send_thread.daemon = True # This must be called before you call start()
Run Code Online (Sandbox Code Playgroud)
如果唯一运行的线程是守护进程,则不会阻止 Python 解释器退出。因此,如果剩下的唯一线程是send_thread,您的程序将退出,即使您在 上被阻塞raw_input。
请注意,这将突然终止发送线程,无论它在做什么。如果它访问需要正确清理或不应中断的外部资源(例如写入文件),这可能会很危险。如果您正在做类似的事情,请使用 保护它threading.Lock,并且仅sys.exit()在可以获取相同的情况下才从接收线程调用Lock。
| 归档时间: |
|
| 查看次数: |
2609 次 |
| 最近记录: |