跨线程对象创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //正确方式1 QThread* thread = new QThread; networkMgr_ = new QNetworkAccessManager; timer_ = new QTimer(networkMgr_); //moveToThread会将networkMgr_,timer_都归属到thread networkMgr_->moveToThread( thread ); thread ->start(); //正确方式2 QThread* thread = new QThread; networkMgr_ = new QNetworkAccessManager; networkMgr_->moveToThread( thread ); timer_ = new QTimer(networkMgr_); timer_->moveToThread( thread ); thread ->start(); //错误方式 QThread* thread = new QThread; networkMgr_ = new QNetworkAccessManager; networkMgr_->moveToThread( thread ); //timer_和networkMgr_不在同一线程 timer_ = new QTimer(networkMgr_); thread ->start(); |
总结: 跨线程创建的对象一定要movetothread。如果是创建时传递父对象,子对象会和父对象工作在同一个线程,但是会有警告,可能会有隐藏问题。另外movetoThread会把该对象的子对象一起归属到新的线程
跨线程对象销毁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //networkMgr_ ,timer_销毁 //正确方式1 (推荐) thread -> exit (); thread ->wait(); networkMgr_->deleteLater(); timer_->deleteLater(); thread ->deleteLater(); //正确方式2 connect( thread ,&QThread::finished,networkMgr_,[ this ](){ delete networkMgr_; delete timer_; }); thread -> exit (); thread ->deleteLater(); //错误方式 delete networkMgr_; delete timer_; |
线程内对象销毁必须在在所属线程,deleteLater可以辅助完成这个工作,deleteLater是往对象当前所属线程的事件队列中放入了一个销毁事件,在合适的时候销毁delete该对象。跨线程直接调用delete可能会导致Crash