【发布时间】:2018-02-03 12:34:10
【问题描述】:
我有一个基于 gsoap 构建的服务器。 Gsoap 也是在 Qt 上编写的。所以我可以使用 Qt 类。
我从客户端向服务器发送请求。
请求如下: 服务器提供了应发送给他的电话号码和消息。这个列表可能有 10 000 或更多,这正是问题所在!我将使用 QThread 向每个号码发送一条消息。当QThread结束它的工作时,应该记录数据库的历史。问题是我们无法理解什么时候所有的历史都记录在数据库中。
我知道这是对问题的一个非常糟糕的解释!请原谅我的英语。
现在我将尝试向您展示该程序的问题。
我有一个 QThread 类,用于发送消息。一个历史类,在数据库中写入历史。
void MainWindow::on_pushButton_clicked() //Imagine that this is a server function.
{
QSet<int> st; //List to who sends a message.
st << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10;
QSet<int> clientAnswer = this->start(st);
qDebug() << "newSet: " << clientAnswer;
//return ClientAnswer list ot client.
}
QSet<int> MainWindow::start(QSet<int> st)
{
for (auto it : st) {
MyThread *thrd = new MyThread(it);
History *hist = new History();
connect(thrd, &MyThread::smsSended, hist, &History::insertHistory);
connect(hist, &History::historyAdded, this, [=](int historyUID){
qDebug() << "history inserted: " << historyUID;
this->ansSet.insert(historyUID);
if (this->ansSet.size() == st.size()) {
qDebug() << "mainwindow finished!";
emit alreadyDone();
}
});
connect(thrd, &MyThread::finished, hist, &History::deleteLater);
connect(thrd, &MyThread::finished, thrd, &MyThread::deleteLater);
thrd->start();
}
return this->ansSet;
}
MainWindow.h
private:
Ui::MainWindow *ui;
QSet<int> ansSet; //The list is to send a client.
MyThread.cpp:
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(int tInt, QObject *parent = 0);
signals:
void smsSended(int);
public slots:
void run();
private:
int m_int;
};
MyThread.h
MyThread::MyThread(int tInt, QObject *parent) : QThread(parent)
{
this->m_int = tInt;
}
void MyThread::run()
{
qDebug() << "thread started: " << this->m_int;
emit smsSended(this->m_int * 10);
}
History.cpp
History::History(QObject *parent) : QObject(parent)
{
}
void History::insertHistory(int insertInt)
{
qDebug() << "insert History: " << insertInt;
emit historyAdded(insertInt);
}
History.h
class History : public QObject
{
Q_OBJECT
public:
explicit History(QObject *parent = 0);
signals:
void historyAdded(int hInt);
public slots:
void insertHistory(int insertInt);
};
应用程序输出如下:
thread started: 5
thread started: 1
thread started: 3
thread started: 2
thread started: 4
thread started: 7
thread started: 9
thread started: 6
newSet: QSet()
thread started: 8
thread started: 10
insert History: 50
history inserted: 50
insert History: 10
history inserted: 10
insert History: 30
history inserted: 30
insert History: 20
history inserted: 20
insert History: 40
history inserted: 40
insert History: 70
history inserted: 70
insert History: 90
history inserted: 90
insert History: 60
history inserted: 60
insert History: 80
history inserted: 80
insert History: 100
history inserted: 100
mainwindow finished!
我知道这个输出是正确的。但是当发生 if (this->ansSet.size() == st.size()) 时,我怎么能从 MainWindow :: start 函数返回一个 QSet ---> ansSet ?或者你有什么想法?
伙计们,我很抱歉我的英语:)
【问题讨论】:
标签: c++ qt synchronization qthread gsoap