durbrak
12th March 2009, 18:39
Hello there,
I'm new to the whole Multithreaded programming and I'm having issues.
functions.h
namespace Functions
{
bool existsInDB(int id);
}functions.cpp
#include "functions.h"
#include <QMutex>
#include [...]
QMutex mutex(QMutex::Recursive);
bool Functions::existsInDB(int id)
{
static QList<int> cache;
QMutexLocker lock(&mutex);
if(cached.contains(id))
return true;
else
{
cached.append(id);
QSqlQuery query;
query.prepare("SELECT COUNT(id) FROM customers WHERE id=?;");
query.addBindValue(id);
query.exec();
query.next();
return (query.value(0).toInt() > 0)
}
}
Now I have a subclass of QThread:
void myThread::run()
{
bool exists = Functions::existsInDB(data->id);
if(exists) {...}
}
As you can see it calls existsInDB(). Now in the main-thread (GUI-Thread) there a sometimes also calls to existsInDB() which causes the following errors to occur in the console (can't remember the exact words):
QSqlQuery::value not positioned on a valid row
If I remove the existsInDB() call in the GUI thread the error disappears. If I remove the existsInDB() call in myThread the error also disappears. So I guess the problem is that both threads are trying to access that function at the same time or something but I can't wrap my head around that whole QMutex story and how to make it work? Can someone point me in the right direction?
Thank you.
I'm new to the whole Multithreaded programming and I'm having issues.
functions.h
namespace Functions
{
bool existsInDB(int id);
}functions.cpp
#include "functions.h"
#include <QMutex>
#include [...]
QMutex mutex(QMutex::Recursive);
bool Functions::existsInDB(int id)
{
static QList<int> cache;
QMutexLocker lock(&mutex);
if(cached.contains(id))
return true;
else
{
cached.append(id);
QSqlQuery query;
query.prepare("SELECT COUNT(id) FROM customers WHERE id=?;");
query.addBindValue(id);
query.exec();
query.next();
return (query.value(0).toInt() > 0)
}
}
Now I have a subclass of QThread:
void myThread::run()
{
bool exists = Functions::existsInDB(data->id);
if(exists) {...}
}
As you can see it calls existsInDB(). Now in the main-thread (GUI-Thread) there a sometimes also calls to existsInDB() which causes the following errors to occur in the console (can't remember the exact words):
QSqlQuery::value not positioned on a valid row
If I remove the existsInDB() call in the GUI thread the error disappears. If I remove the existsInDB() call in myThread the error also disappears. So I guess the problem is that both threads are trying to access that function at the same time or something but I can't wrap my head around that whole QMutex story and how to make it work? Can someone point me in the right direction?
Thank you.