#include <QtCore>
#include <signal.h>
{
public:
, m_semaphore(s)
, m_id(id)
, m_stop(false)
{
}
void stop()
{
m_stop = true;
}
void run()
{
qDebug() << "Starting secondardy thread" << m_id;
while(!shouldStop()) {
msleep(10);
}
qDebug() << "Secondary thread" << m_id << "exiting";
m_semaphore.release();
}
private:
int m_id;
bool m_stop;
private:
bool shouldStop() const
{
return m_stop;
}
};
void signalHandler(int signalNumber)
{
qDebug() << Q_FUNC_INFO << signalNumber;
}
int main(int argc, char **argv)
{
signal(SIGINT, signalHandler);
signal(SIGTERM, signalHandler);
QVector<Thread*> threads(10);
for (int i = 0; i < threads.count(); ++i) {
threads[i] = new Thread(semaphore, i);
threads[i]->start();
}
qDebug() << "Starting Main thread event loop";
int ret = app.exec();
for (int i = 0; i < threads.count(); ++i) {
threads[i]->stop();
}
semaphore.acquire(threads.count());
qDeleteAll(threads);
qDebug() << "Main thread exiting";
return ret;
}
#include <QtCore>
#include <signal.h>
class Thread : public QThread
{
public:
explicit Thread(QSemaphore &s, int id, QObject *parent = 0)
: QThread(parent)
, m_semaphore(s)
, m_id(id)
, m_stop(false)
{
}
void stop()
{
QMutexLocker locker(&m_mutex);
m_stop = true;
}
void run()
{
qDebug() << "Starting secondardy thread" << m_id;
while(!shouldStop()) {
msleep(10);
}
qDebug() << "Secondary thread" << m_id << "exiting";
m_semaphore.release();
}
private:
mutable QMutex m_mutex;
QSemaphore &m_semaphore;
int m_id;
bool m_stop;
private:
bool shouldStop() const
{
QMutexLocker locker(&m_mutex);
return m_stop;
}
};
void signalHandler(int signalNumber)
{
qDebug() << Q_FUNC_INFO << signalNumber;
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
signal(SIGINT, signalHandler);
signal(SIGTERM, signalHandler);
QSemaphore semaphore(0);
QVector<Thread*> threads(10);
for (int i = 0; i < threads.count(); ++i) {
threads[i] = new Thread(semaphore, i);
threads[i]->start();
}
qDebug() << "Starting Main thread event loop";
int ret = app.exec();
for (int i = 0; i < threads.count(); ++i) {
threads[i]->stop();
}
semaphore.acquire(threads.count());
qDeleteAll(threads);
qDebug() << "Main thread exiting";
return ret;
}
To copy to clipboard, switch view to plain text mode
Bookmarks