
Originally Posted by
strateng
I only have one class so I was wondering if I would be able to multithread within it so that I am able to run more than one function at a time?
Short answer: no, you can’t do that.
The long answer — why you can’t, and under what circumstances you might be able to do something that is technically what you said, but almost surely not what you want — you’ll have to understand by reading the Qt documentation. Start at Thread Support in Qt.
Following is a partial “example†of using QThread in the situation you described. I haven’t tested it, so it might contain typos, omissions and/or major blunders, but perhaps it will help you:
class connectionInfo {
//...
};
void functionThatGetsAConnection(connectionInfo*);
class getConnection
: public QThread { Q_OBJECT
public:
connectionInfo info;
getConnection() {moveToThread(this);}
protected:
void run() {
functionThatGetsAConnection(&info);
emit gotConnection(this);
}
signals:
void gotConnection(getConnection*);
};
// within your class (which must derive from QObject):
Q_OBJECT
private:
QList<getConnection*> connections;
private slots:
void gotConnection(getConnection*);
// to look for a new connection:
getConnection* con = new getConnection();
connections += con;
connect (con, SIGNAL(gotConnection(getConnection*)), SLOT(gotConnection(getConnection*)), Qt::QueuedConnection);
con->start();
// in gotConnection(getConnection* con):
// ... code that uses con->info ...
connections.removeOne(con);
delete con;
class connectionInfo {
//...
};
void functionThatGetsAConnection(connectionInfo*);
class getConnection : public QThread {
Q_OBJECT
public:
connectionInfo info;
getConnection() {moveToThread(this);}
protected:
void run() {
functionThatGetsAConnection(&info);
emit gotConnection(this);
}
signals:
void gotConnection(getConnection*);
};
// within your class (which must derive from QObject):
Q_OBJECT
private:
QList<getConnection*> connections;
private slots:
void gotConnection(getConnection*);
// to look for a new connection:
getConnection* con = new getConnection();
connections += con;
connect (con, SIGNAL(gotConnection(getConnection*)), SLOT(gotConnection(getConnection*)), Qt::QueuedConnection);
con->start();
// in gotConnection(getConnection* con):
// ... code that uses con->info ...
connections.removeOne(con);
delete con;
To copy to clipboard, switch view to plain text mode
Note particularly that missing from the above is code to clean up getConnections that either never find a connection (time out, or simply fail), or that are still actively looking for a connection when your class is destroyed. Those matters must be addressed, but how to do it is dependent on how functionThatGetsAConnection handles time outs, failures and requests to stop trying.
Bookmarks