class scraper: public QRunnable
{
private:
int _id;
QMutex& _mtx;
public:
scraper
(int id, QMutex
& m,
QString p
) : _id
(id
), _mtx
(m
), _path
(p
) {} void run() {
qfs.addPath(_path);
// this slot is never called, despite moving file to the path. I think it is because it executes in the main thread;
if (! QObject::connect(&qfs,
&QFileSystemWatcher
::directoryChanged,
[&](const QString
& p
){ qDebug
() <<
"cycle:" <<
QString::number(_id
) <<
"file:" <<p;
_mtx.unlock();
})) {
qDebug() << "failure to connect to QFileSystemWatcher::directoryChanged signal";
return;
}
qDebug
() <<
"waiting for file in cycle " <<
QString::number(_id
);
}
};
int main(int argc, char *argv[])
{
qDebug()<< "started";
QTimer::singleShot(2000,
&a,
[&](){ for (int i = 0; i < 20; ++i) {
qDebug
() <<
"starting cycle " <<
QString::number(i
);
scraper* myscraper = new scraper(i, mtx, pt);
QThreadPool::globalInstance()->start(myscraper);
mtx.lock();
wc.wait(&mtx, 20000);
mtx.unlock();
}
});
return a.exec();
}
class scraper: public QRunnable
{
private:
int _id;
QMutex& _mtx;
QString _path;
public:
scraper(int id, QMutex& m, QString p) : _id(id), _mtx(m), _path(p) {}
void run() {
QFileSystemWatcher qfs;
qfs.addPath(_path);
// this slot is never called, despite moving file to the path. I think it is because it executes in the main thread;
if (! QObject::connect(&qfs, &QFileSystemWatcher::directoryChanged, [&](const QString& p){
qDebug() << "cycle:" << QString::number(_id) << "file:" <<p;
_mtx.unlock();
})) {
qDebug() << "failure to connect to QFileSystemWatcher::directoryChanged signal";
return;
}
qDebug() << "waiting for file in cycle " << QString::number(_id);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<< "started";
QMutex mtx;
QString pt="c:/temp/files";
QWaitCondition wc;
QTimer::singleShot(2000,&a, [&](){
for (int i = 0; i < 20; ++i) {
qDebug() << "starting cycle " << QString::number(i);
scraper* myscraper = new scraper(i, mtx, pt);
QThreadPool::globalInstance()->start(myscraper);
mtx.lock();
wc.wait(&mtx, 20000);
mtx.unlock();
}
});
return a.exec();
}
To copy to clipboard, switch view to plain text mode
The issue I am having is that the signal directoryChanged is never called. I think it is because it is a queued call and it is executed in the context of the main thread which is blocked. Perhaps I should use QThread instead of QRunnable? Suggestions and critiques are always welcomed and appreciated. Thanks!
Bookmarks