Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
New Developer
sharath_moblie
Posts: 104
Registered: ‎09-25-2013
My Device: BB 10

qthread destroyed while thread still running

[ Edited ]

Hi Friends,

 

I am geting this error, " qthread destroyed while thread still running "  error on the console and terminating the app immediately. In my app, I am wiritng socket programming and updating the data for each second by using timers( creating a timer object in the Qml  and  making a function call for each second to update the data in a ist view)

 

void messageLogger(QtMsgType type, const char *msg) {
std::fprintf(stdout, "%s\n", msg);
std::fflush(stdout);
}
Q_DECL_EXPORT int main(int argc, char **argv)
{
   
	Application app(argc, argv);
	Client *client = new Client();
	
		    QThread *thread = new QThread(&app);
		        thread->start();
		        client->moveToThread(thread);
		        MyThread th;
		        th.startMyThread();


    qInstallMsgHandler(messageLogger);
    return Application::exec();
}

 MyThread.cpp is as follows.

#include "MyThread.h"
unsigned int delay(unsigned int duration);

MyThread::MyThread()
{
	// TODO Auto-generated constructor stub

}

MyThread::~MyThread()
{
	// TODO Auto-generated destructor stub
}
void MyThread::startMyThread(){

	start();
}
void MyThread::run()
 {

     while(true){
    	Client::s_instance->worker();
    	 sleep(1);
     }
 }

 

 

Client.h  and It's corresponding Client.cpp is posted here.

 

#ifndef CLIENT_H_
#define CLIENT_H_

#include <QtNetwork/qtcpsocket.h>
#include <unistd.h>
#include <stdlib.h>
#include <qtextstream.h>
#include <QObject>
#include <QTimer.h>
#include "applicationui.hpp"
#include <bb/system/SystemToast>
#include <bb/system/SystemUiPosition>
#include <bb/system/SystemListDialog>

unsigned int delay(unsigned int duration);
using namespace bb::system;
class Client: public QObject
{
Q_OBJECT
public:
ApplicationUI *app;
		Client()
	 	{
			s_instance= this;
	 		//reconnect(host,port);
	 	}
		 static Client *s_instance;
	virtual ~Client()
	{
	}
	void worker();
	void reconnect(const QString &host, const ushort port);

	 static Client& instance();

	 void setIp(const QString &host1,const ushort port1,ApplicationUI *_app){
		 host=host1;
		 port=port1;
		 app=_app;
		 reconnect(host1,port1);
	 }
	 bool isNetworkAvailable();
	 void  HttpPost(QString URL);

public slots:

	void closeConnection();
	void socketConnected();

	void socketConnectionClosed();

	void sendToServer();

	void socketClosed();

	void reqSymbols(QString req);

	void socketReadyRead();

	void socketError(QAbstractSocket::SocketError socketError);



private slots:
	 void   HttpResponse(QNetworkReply* reply);

private:
	QTcpSocket *socket;
	QString remaining;
	 QString host;
	 ushort port;

};

#endif /* CLIENT_H_ */

 


#include <QtNetwork/qtcpsocket.h> #include <qtextstream.h> #include <qtconcurrentrun.h> #include<Client.h> #include<QtCore/QStringList> #include "Helper.h" #include <bb/data/JsonDataAccess> #include "DatabaseOperations.h" #include <unistd.h> #include <stdlib.h> #include <QtNetwork/qnetworkconfiguration.h> #include <QtCore/QList> #include "ClientReq.h" #include "DatabaseOperations.h" #include <bb/data/JsonDataAccess> #include <QByteArray> #include "Helper.h" #include <QThread> #include <QtNetwork/qnetworkconfiguration.h> #include <bb/device/HardwareInfo.hpp> #include "SubcriptDB.h" #include "SocketBase.h" #include "Helper.h" #include "AlertsList.h" #include <bb/cascades/Application> #include <QtNetwork/qtcpsocket.h> #include <QtCore/qthread.h> #include <QtCore/qdebug.h> #include <bb/cascades/JavaScriptWorld> #include <bb/cascades/Label> #include <QtCore/QList> #include <unistd.h> #include <stdlib.h> #include<QList> #include <QByteArray> #include <bb/data/JsonDataAccess> #include <unistd.h> #include "DatabaseOperations.h" #include "applicationui.hpp" #include <QtNetwork/qnetworkconfiguration.h> #include <bb/device/HardwareInfo.hpp> #include <bb/system/SystemToast> #include <bb/system/SystemUiPosition> #include <bb/system/SystemListDialog> #include <QObject> #include <QtSql/QtSql> #include <QDebug> #include <QLocale> QString reqType; using namespace bb::cascades; using namespace bb::data; //using namespace bb::system; using namespace bb::device; unsigned int delay(unsigned int duration); int isReconnect = -1; bool isReconnected = false; SystemDialog * dialogExit22; bool IsDonePre; int Con_Count = 0; bool isReading = false; Client* Client::s_instance = 0; bool noInternet=false,gotRes=false; bool isDone = false; bool isDone1 = false; QString Helper; QByteArray data(""); int counter = 1; //QNetworkAccessManager *mNetworkAccessManager; unsigned int delay(unsigned int duration); void Client::reconnect(const QString &host, const ushort port) { socket = new QTcpSocket(this); connect(socket, SIGNAL(connected()), SLOT(socketConnected())); connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError))); socket->connectToHost(host, port); if (socket->waitForConnected(1000)) { printf("\n ***********waitForConnected*********Connected"); } if (socket->state() == QAbstractSocket::ConnectedState){ printf("\n ***********socket state*********Connected"); isReconnect = 1; } else{ printf("\n ***********socket state*********Not connected"); HttpPost("https://www.google.co.in/"); } } void Client::socketConnected() { qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^ socketConnected"; QString dev_id = Helper::device_pin; QString type = Helper::userType; QString conData = "Login:" + dev_id + "," + dev_id + "," + dev_id + "," + type + ",blackberry"; qDebug() << "777777777777" << conData; int returnval = socket->write(conData.toAscii()); if (!socket->waitForBytesWritten()) { printf("writeLine: the write to the socket failed\n"); } else { qDebug() << " \n Connection Data Client::sendToServer" << conData<< " " << returnval; } } void Client::reqSymbols(QString req) { Helper::clearSymbolsList(); // clear the previos request stack Helper::tailrequest = req; reqType = req; qDebug() << "\n #################################### reqSymbols " + req; int returnval = socket->write(req.toAscii()); if (!socket->waitForBytesWritten()) { printf("\n reqSymbols: the write to the socket failed\n"); } else { qDebug() << " \n reqSymbols " << " " << returnval; } } void Client::worker() { //if(Helper::setSeen){ if (IsDonePre && !isReading && socket->state() == QAbstractSocket::ConnectedState) { if (Helper::reqText != "") { qDebug()<< "\n !!!!!!!!!!!!!!!!!!!!! req from worker method !!!!!!!!!!!!!!!!!!!!!!!"; reqSymbols(Helper::reqText); Helper::tailrequest = Helper::reqText; Helper::reqText = ""; } } if (isReconnect == 1 ) { qDebug()<<"\n **************request when reconnected"; isReconnect = -1; reqSymbols(Helper::tailrequest); } } void Client::socketReadyRead() { //qDebug() << "\n init socketReadyRead called"; int bytesAvail = -1; isReading = true; bytesAvail = socket->bytesAvailable(); data.append(socket->readAll()); isReading = false; QString resData = QString(data); data.clear(); int currentTime = QDateTime::currentMSecsSinceEpoch() / 1000; //qDebug() << " \n ****" << " " << currentTime << " " << resData; //******** for Only Fresh Login ********** if(resData == "LoginStatus:1"){ qDebug()<<"<<<<<<<<<<<<<<<<<<<<<<< Log in Ok >>>>>>>>>>>"; resData=""; data.clear(); // clear other wise Added to Helper::requestAll if(!Helper::isReq_All){ qDebug()<<"<<<<<<<<<<<<<<<<<<<<<<< sending RequestSymbols:All >>>>>>>>>>>"; Helper::requestAll = ""; reqSymbols("RequestSymbols:All"); } Helper::isLogin = true; return; } // ******** for Only Request All ********** if (reqType == "RequestSymbols:All" ) { //if(!resData.endsWith(']')) qDebug()<<"reading request all >>>>>>>>>>>"; Helper::requestAll += resData; //qDebug() << "\n Helper::requestAll"<<Helper::requestAll; if(resData.endsWith(']')){ qDebug()<<"<<<<<<<<<<<<<<<<<<<<<<< Finished reading request all >>>>>>>>>>>"; reqSymbols(Helper::reqText); Helper::reqText=""; Helper::isReq_All=true; IsDonePre = true; } return; } // For Reading if (resData.length() > 0 ) { //QString line=""; bool skipremaining = false; QString ba; if(resData.startsWith("{")){ ba = resData; }else{ ba = remaining +resData; } //data.clear(); QStringList testList = ba.split('}'); JsonDataAccess jda; for (int i = 0; i < testList.size(); i++) { // qDebug() << "\n Socket read this:: \n " << i << testList.at(i); if (testList.at(i) != "") { //qDebug() << "\n Socket read this:: \n " << i << testList.at(i); QString temp; if (testList.at(i) != "]" && testList.at(i) !="LoginStatus:1") { // somes times (quick watch recoonect) "LoginStatus" adding to temp temp = "[" + testList.at(i) + "}]"; // qDebug()<<i; } //qDebug()<<"\n Socket read this:: \n "<< temp; QVariantList data = jda.loadFromBuffer(temp).toList(); //qDebug()<<"data size:::::"<<data.size(); if (!jda.hasError()) { Helper::dataString += testList.at(i) + "},"; Helper::counter++; } else { //qDebug()<<"\n json error socketReadyRead \n \n "; // qDebug() << " !!!!!!!!!!!AlertStatus:::"<<testList.at(i); QString com=testList.at(i); if (com.contains("AlertStatus")) { bool isBool; QString str = testList.at(i); qDebug() << str.split("AlertStatus:"); QString temp = testList.at(i).split("AlertStatus:").at(1); QString temp1 = temp.split(';').at(0); QString temp2 = temp1.split(',').at(0); QString temp3 = temp1.split(',').at(1); int serverid = temp2.toInt(&isBool); // EURUSD is reached : 1.444564 DatabaseOperations::updateAlertServerId(temp3,serverid); // app->alertShow(serverid); // com="AlertExecuted:"+ QString::number(serverid)+";"; skipremaining = true; } if (com.contains("AlertExecuted")) { bool isBool; // QString str = testList.at(i); QString str = com; QString temp = str.split("AlertExecuted:").at(1); QString temp1 = temp.split(';').at(0); qDebug()<<"\n temp1 @@@@@@@@@"<<temp1; int serverid = temp1.toInt(&isBool); app->alertShow(serverid); skipremaining = true; } if (!skipremaining && i + 1 == testList.size()) { remaining = testList.at(i); } } } } } } void Client::HttpPost(QString URL ){ QNetworkRequest request = QNetworkRequest(); request.setUrl(QUrl(URL)); QNetworkAccessManager *mNetworkAccessManager = new QNetworkAccessManager(this); bool result=connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(HttpResponse(QNetworkReply *))); //qDebug() << result; mNetworkAccessManager->get(request); //printf("::: Request made to Service :::"); qDebug() << "\n ::: Client.cpp Request made to Service :::"; } void Client::HttpResponse(QNetworkReply* reply) { if (reply->error() == QNetworkReply::NoError) { gotRes=true; qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^ socketError"; if (isReconnect == -1 || isReconnect == 1) { qDebug() << "\n Trying to reconnect"; delay(5000); reconnect("XXX.XXX.XXX.XXX", ABC); } } else { //qDebug() << "\nData from yahoo ::: Problem with the network"; qDebug() << "\n No Internet **********" << reply->errorString(); //showDialog(-1000); app->alert("please try again, if failed again restart the application"); QCoreApplication::processEvents(); gotRes=true; noInternet=true; } } void Client::socketConnectionClosed() { qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^ socketConnectionClosed"; } void Client::socketClosed() { qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^ socketClosed"; } void Client::socketError(QAbstractSocket::SocketError socketError) { HttpPost("https://www.google.co.in/"); } void Client::closeConnection() { socket->close(); if (socket->state() != QAbstractSocket::ConnectedState) { // We have a delayed close. connect(socket, SIGNAL(delayedCloseFinished()), SLOT(socketClosed())); } else { // The socket is closed. socketClosed(); } } void Client::sendToServer() { } Client& Client::instance() { if (!s_instance) s_instance = new Client(); return *s_instance; } bool Client::isNetworkAvailable() { bool isFound = false; QNetworkConfigurationManager netMgr; QList<QNetworkConfiguration> mNetList = netMgr.allConfigurations( QNetworkConfiguration::Active); if (mNetList.count() > 0) { if (netMgr.isOnline()) { isFound = true; } } qDebug() << "\n ************** isNetworkAvailable:::" << isFound; return isFound; }

 and my ApplicationUI is like, 

ApplicationUI::ApplicationUI(bb::cascades::Application *app){

	//QList<int> test;

	try {
		fapp=app;

		_app = app;
		 Client::s_instance->setIp(IP, port,this );

		

		initDataModel();

		DatabaseOperations::initDatabase();

		// Registering the timer with Qml
		qmlRegisterType < Timer > ("CustomTimer", 1, 0, "Timer");
		qmlRegisterType < AddOrDeleteSymbols
				> ("my.library", 1, 0, "QAddOrDeleteSymbols");

		// create scene document from main.qml asset
		// set parent to created document to ensure it exists for the whole application lifetime
		qml = QmlDocument::create("asset:///Template.qml").parent(this);
		QmlDocument *qmll = QmlDocument::create("asset:///langSelection.qml");
	
		 QObject::connect(app, SIGNAL( manualExit() ), this,
				SLOT( onManualExit() ));

		drop_Req = this;
		qml->setContextProperty("_app", this);
		qmll->setContextProperty("_app", this);
		qml->setContextProperty("_wapp", app);

		// create root object for the UI
		root = qml->createRootObject<TabbedPane>();
		QObject *objTab = root->findChild<QObject*>("objTab");//objTab2
		Tab *objTab2 = root->findChild<Tab*>("objTab2");
		Tab *objTab3 = root->findChild<Tab*>("objTab3");

		navTab = root->findChild<NavigationPane*>("objNavigationPane");
		navTab2 = root->findChild<NavigationPane*>("objNavigationPane2"); // objectName: "navTab3"
		navTab3 = root->findChild<NavigationPane*>("objNavTab3");

		loader=root->findChild<Container*>("loader");
		myIndicator=root->findChild<ActivityIndicator*>("myIndicator");

		loaderTab2=root->findChild<Container*>("loaderTab2");
		myIndicatorTab2=root->findChild<ActivityIndicator*>("myIndicatorTab2");//bannerUpgrade

		loaderTab3=root->findChild<Container*>("loaderTab3");
		myIndicatorTab3=root->findChild<ActivityIndicator*>("myIndicatorTab3");//bannerUpgrade


		// Upgrading the mTadawul App based on user Type (basic or real type)
		bannerUpgrade=root->findChild<Container*>("bannerUpgrade");//objectName: "bannerUpgradeTab3"
		bannerUpgradeTab2=root->findChild<Container*>("bannerUpgradeTab2");
		//bannerUpgradeTab3=root->findChild<Container*>("bannerUpgradeTab3");//tadawulTitle

		if(Helper::userType=="0"){
		bannerUpgrade->setVisible(true);
		bannerUpgradeTab2->setVisible(false);
		//bannerUpgradeTab3->setVisible(false);
		}
		else if(Helper::userType=="1"){
		bannerUpgrade->setVisible(false);
		bannerUpgradeTab2->setVisible(false);
		//bannerUpgradeTab3->setVisible(false);
		}

		translate=root->findChild<Label*>("translate");
		translate2=root->findChild<Label*>("translate2");
		translate3=root->findChild<Label*>("translate3");

		m_pTranslator = new QTranslator(this);
						m_pLocaleHandler = new LocaleHandler(this);

		 if(!QObject::connect(m_pLocaleHandler,
							SIGNAL(systemLanguageChanged()),
							this,
							SLOT(onSystemLanguageChanged()))) {
							// This is an abnormal situation! Something went wrong!
							// Add own code to recover here
							qWarning() << "Recovering from a failed connect()";
						}


		 initLangLoad();// for Language switching
		 QDeclarativePropertyMap* propertyMap = new QDeclarativePropertyMap;
			propertyMap->insert("langSetting", Helper::lang_settings);

			qml->setContextProperty("propertyMap", propertyMap);
			changeOrientation();

		 app->resetScene();
		 app->setAutoExit(false);
		 app->setScene(root);

	} catch (std::exception &e) {
		QString str(e.what());
	}
}

 I found the crashing is happening 

 

1. Immediately after  you opening the app and displaying " qthread destroyed while thread still running" on the console

 

2. Sometimes app is opening and behaving as we expected. and crashing in the middle.

 

3. Sometimes crashing is not found and running smoothly.

 

Kindly help me.I struck at the end of the app. and unablle to release with this Issue. 

 

I request you all to trace this Bug.

 

Thanks !!!