2

python编程(GUI线程和工作线程的同步)

 1 year ago
source link: https://blog.51cto.com/feixiaoxing/5881036
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

    一般来说,编写gui客户端之外,都要编写几个work thread。因为如果只有一个gui thread,在某些socket或者低速io操作的时候,速度是非常慢的,所以这个时候建议多开几个thread,增加用户体验。

    增加几个work thread本身没有问题,但是gui和工作线程沟通是一个问题。一般来说,常用的方法就是在gui线程起一个timer,定时通过queue数据看一下work thread进展如何。这样虽然麻烦一点,至少逻辑上比较保险。今天看了一下wxpython下的处理办法,它使用CallAfter和CallLater、PostEvent这三个方法实现的,还是很受启发的。

1、CallAfter调用

    CallAfter调用很简单,就是work thread调用CallAfter之后,GUI thread来看这个注册的函数和变量,整个流程都是GUI自己完成的,数据也是异步交互的。

#!/usr/bin/python

import os
import sys
import wx

app=wx.App()
f=wx.Frame(None)
f.Show()

def process(data):
f.Close()

wx.CallAfter(process, '123')
app.MainLoop()

2、CallLater调用

    CallLater比CallAfter多一个时间参数,参数的基本单位是ms。所以,这里适用于进展比较缓慢的io操作,一般代码是这样的,

#!/usr/bin/python

import os
import sys
import wx

app=wx.App()
f=wx.Frame(None)
f.Show()

def process(data):
f.Close()

wx.CallLater(3000, process, '123')
app.MainLoop()

3、PostEvent方法

    还有一种方法,就是PostEvent方法。用这种方法有两个地方要注意一下。第一个地方,就是在frame里面需要用Connect函数将event_id和event_handler绑定在一起。第二个地方,就是work thread中先SetEventType,然后在线程run的时候通过PostEvent发送出去就可以了。这样event_handler函数收到信息后,就可以在GUI线程里面继续处理了。具体的使用法法,可以查看这两

    这三种方法都适合gui线程和work thread交互,难易程度依次递增,大家可以根据自己的需求灵活加以运用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK