synchornize Competitive Companion Thread stop.

This commit is contained in:
Roy Qu 2024-05-25 10:19:44 +08:00
parent eb4b21e1f2
commit b489695639
2 changed files with 12 additions and 2 deletions

View File

@ -56,7 +56,7 @@ void CompetitiveCompanionHandler::stop()
return; return;
connect(mThread, &QThread::finished, connect(mThread, &QThread::finished,
mThread, &QObject::deleteLater); mThread, &QObject::deleteLater);
mThread->stop(); mThread->waitStop();
mThread=nullptr; mThread=nullptr;
} }
@ -155,6 +155,7 @@ CompetitiveCompanionThread::CompetitiveCompanionThread(QObject *parent):
mStop{false}, mStop{false},
mBatchProblemsRecieved{0}, mBatchProblemsRecieved{0},
mStartSemaphore{0}, mStartSemaphore{0},
mStopSemaphore{0},
mStartOk{false} mStartOk{false}
{ {
} }
@ -170,6 +171,12 @@ bool CompetitiveCompanionThread::waitStart()
return mStartOk; return mStartOk;
} }
void CompetitiveCompanionThread::waitStop()
{
stop();
mStopSemaphore.acquire(1);
}
void CompetitiveCompanionThread::run() void CompetitiveCompanionThread::run()
{ {
QTcpServer tcpServer; QTcpServer tcpServer;
@ -179,7 +186,7 @@ void CompetitiveCompanionThread::run()
} }
mStartSemaphore.release(1); mStartSemaphore.release(1);
while(!mStop) { while(!mStop) {
tcpServer.waitForNewConnection(100); tcpServer.waitForNewConnection(1000);
while (tcpServer.hasPendingConnections()) { while (tcpServer.hasPendingConnections()) {
QTcpSocket* clientConnection = tcpServer.nextPendingConnection(); QTcpSocket* clientConnection = tcpServer.nextPendingConnection();
onNewProblemConnection(clientConnection); onNewProblemConnection(clientConnection);
@ -187,4 +194,5 @@ void CompetitiveCompanionThread::run()
} }
} }
tcpServer.close(); tcpServer.close();
mStopSemaphore.release(1);
} }

View File

@ -33,6 +33,7 @@ public:
CompetitiveCompanionThread &operator=(const CompetitiveCompanionThread&) = delete; CompetitiveCompanionThread &operator=(const CompetitiveCompanionThread&) = delete;
void stop(); void stop();
bool waitStart(); bool waitStart();
void waitStop();
signals: signals:
void newProblemReceived(int num, int total, POJProblem newProblem); void newProblemReceived(int num, int total, POJProblem newProblem);
// void newBatchReceived(int total); // void newBatchReceived(int total);
@ -48,6 +49,7 @@ private:
int mBatchCount; int mBatchCount;
int mBatchProblemsRecieved; int mBatchProblemsRecieved;
QSemaphore mStartSemaphore; QSemaphore mStartSemaphore;
QSemaphore mStopSemaphore;
bool mStartOk; bool mStartOk;
}; };