• 5171阅读
  • 0回复

[原创]Qt经典—什么时候不需要使用线程 [复制链接]

上一主题 下一主题
离线zjhcool
 
只看楼主 倒序阅读 楼主  发表于: 2011-02-24
计时器

If you think you need threads then your processes are too fat. — Bradley T. Hughes
这也许是线程滥用最坏的一种形式。如果我们不得不重复调用一个方法(比如每秒),许多人会这样做:
view plaincopy to clipboardprint?
// 非常之错误
while (condition) {
doWork();
sleep(1); // this is sleep(3) from the C library
}



然后他们发现这会阻塞事件循环,因此决定引入线程
view plaincopy to clipboardprint?
// 错误
class Thread : public QThread {
protected:
void run() {
while (condition) {
// notice that "condition" may also need volatiness and mutex protection
// if we modify it from other threads (!)
doWork();
sleep(1); // this is QThread::sleep()
}
}
};



一个更好也更简单的获得相同效果的方法是使用timers,即一个QTimer[doc.qt.nokia.com]对象,并设置一秒的超时时间,并让doWork方法成为它的槽:
view plaincopy to clipboardprint?
class Worker : public QObject
{
Q_OBJECT
public:
Worker() {
connect(&timer, SIGNAL(timeout()), this, SLOT(doWork()));
timer.start(1000);
}
private slots:
void doWork() {
/* ... */
}
private:
QTimer timer;
};



所有我们需要做的就是运行一个事件循环,然后doWork()方法将会被每隔秒钟调用一次。
..
标签: Qt, 线程
本文链接: Qt经典—什么时候不需要使用线程
版权所有: Venus, 转载请注明来源Venus并保留链接地址!


相关文章


我的博客地址: http://newfaction.net
快速回复
限100 字节
 
上一个 下一个