Hi,
I cannot stop a thread.
main.cpp
#include <QCoreApplication>
#include "mythread.h"
int main(int argc, char *argv[])
{
MyThread mThread1;
mThread1.name = "mThread1";
mThread1.start();
mThread1.stop = true;
return a.exec();
}
#include <QCoreApplication>
#include "mythread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread mThread1;
mThread1.name = "mThread1";
mThread1.start();
mThread1.stop = true;
return a.exec();
}
To copy to clipboard, switch view to plain text mode
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QtCore>
{
public:
MyThread();
void run();
bool stop;
};
#endif // MYTHREAD_H
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QtCore>
class MyThread : public QThread
{
public:
MyThread();
void run();
QString name;
bool stop;
};
#endif // MYTHREAD_H
To copy to clipboard, switch view to plain text mode
mythread.cpp
#include "mythread.h"
#include <QDebug>
MyThread::MyThread()
{
}
void MyThread::run() {
qDebug() << this->name << " Running";
mutex.lock();
this->stop = false;
mutex.unlock();
for (int i = 0; i < 1000; i++) {
mutex.lock();
if (this->stop) {
break;
}
mutex.unlock();
this->sleep(1);
qDebug() << this->name << " " << i;
}
}
#include "mythread.h"
#include <QDebug>
MyThread::MyThread()
{
}
void MyThread::run() {
qDebug() << this->name << " Running";
QMutex mutex;
mutex.lock();
this->stop = false;
mutex.unlock();
for (int i = 0; i < 1000; i++) {
QMutex mutex;
mutex.lock();
if (this->stop) {
break;
}
mutex.unlock();
this->sleep(1);
qDebug() << this->name << " " << i;
}
}
To copy to clipboard, switch view to plain text mode
It's the example from this video: http://www.youtube.com/watch?v=5WEiQ3VJfxc
Thank you!
Bookmarks