|
原帖由 GPS 于 12-7-2010 12:40 发表
我再看看哪里出问题了。
刚看了你上面的两个链接,真是切中要害阿,呵呵,一直就在琢磨这个一段时间了。
总结一下理解,看看对不对。
第一篇里,QThread里默认的run()已经启动了消息循环exec(). 当需要新线程时 ...
另一种方式也不错,有些情况下必须subclass QThread, 错的不是是否subclass,错在:subclassing QThread, adding signal and slot code to that subclass, and then calling moveToThread(this);
To set the record straight: I’m not saying sub-classing QThread is wrong. This is also how Java does it (sort of), and many people have been doing this with Qt for a long time.
What I’m saying is “wrong” is subclassing QThread, adding signal and slot code to that subclass, and then calling moveToThread(this); in the constructor of that subclass. This causes people lots of confusion from my experience and observation on the #qt channel and the qt-interest mailing list.
And yes, the current docs are still a bit lacking, something that I am fully aware of (and take responsibility for). I’m planning on sitting down and fleshing them out, showing both ways of using QThread (with and without subclassing).
在Qt的编程模型里,thread和signal-slot都是实现异步编程的手段,signal-slot的背后是消息循环,而每个thread都是一个独立的消息循环,在早期版本,qt线程间无法进行signal-slot消息传递,这就导致了各个消息循环都是互相独立的loop, 通讯的唯一方式只剩下global state+ mutex lock。在4.x 之后,signal-slot已经能够和thread融洽相处了。
这样,理想的QT编程模型就变成了独立的一个个任务,各自使用自己的thread和thread内部消息循环,在需要互相通讯的时候,使用signal-slot, 这些signal和slot就是明确定义的消息接口,除此之外,最好不共享其它状态。Qt程序员有点像转盘子的杂技演员,每个盘子都独自转动,整个系统由很多旋转的盘子组成,这些盘子可以共享杂技演员一个手,也可以是另一只手甚至不同的杂技演员来控制(多CPU)。
[ 本帖最后由 coredump 于 12-7-2010 12:55 编辑 ] |
|