synchronizing slots in QThread -? - qt

I have 2 slot handlers in QThread- derived class: one is timer handler and another is just asynchronous callback handler. Both have to modify the same data.
struct somedata {
int max;
int min;
double avg;
}
...
class MyThread: QThread {
private:
somedata m_data;
private Q_SLOTS:
void asyncCallback(int a, int b) {
m_data.max += a;
m_data.min += b;
}
void timer() {
m_data.avg =(m_data.a + m_data.b)/2;
}
}
Should the access to m_data be serialized in some fashion, although both method are in the same thread?
Thanks,

As long as you can guarantee that your data is only ever being accessed or modified by a single thread at any time, then you don't need to work about synchronizing access to that data via thread-safety constructs.
One way to verify this is to check the return value of QThread's static currentThread() function when your functions are called.

If both functions are called by same thread then you dont need to worry about the data getting changes when the other call is in the second slot.If you are not sure then the best option is to use a mutex in both the slots so that only one process or changes the value of m_data.

Related

breaking a loop called inside the slot of a QObject living in a thread

AcquisitionManager is a QObject living in a thread, I use it to acquire samples from an acquisition PCI-Express card :
m_acquisitionThread = new QThread(this);
m_acquisitionManager = new AcquisitionManager();
m_acquisitionManager->moveToThread(m_acquisitionThread);
m_acquisitionThread->start();
In my application code (living in the main thread), I use this :
QMetaObject::invokeMethod(m_acquisitionManager, "executeDataAcquisition", Qt::QueuedConnection);
to launch data acquisitions.
Inside 'executeDataAcquisition' slot, I have a loop :
for (size_t i = 0; i < numberOfLoops; ++i)
{
// blocking calls...
}
Sometimes, I want the user to abort acquisitions ASAP, I thought about using a boolean variable (+ volatile) that I modify from the main thread. Even if this isn't very thread safe, the boolean variable is only read by the 'slave' thread and only written by the master thread (main) :
for (size_t i = 0; i < numberOfLoops && m_bKeepAcquiring; ++i)
{
// blocking calls...
}
Is it right to do so ? I saw this technique in a lot of software I worked on but I don't know if it's safe to do so. Is there another technique ?
Well with "even if this isn't very thread safe" this becomes a bit of a code style question really. I mean if you don't care about direct cross-thread access then I guess it doesn't matter.
Personally I probably would not do it that way. It's pretty simple to add a method to the worker thread to set the "stop" flag (and even protect the flag with a simple mutex like QReadWriteLock). Then the stop can be ordered "properly" with a signal or queued meta method invocation. If the flag isn't likely to be set from anywhere except a main controller thread, skipping a mutex might be fine, though it's also fairly cheap insurance.
class AcquisitionManager ... {
public slots:
void requestStop() {
QWriteLocker lock(&m_flagMutex);
m_bStopRequested = true;
}
void executeDataAcquisition() {
for (size_t i = 0; i < numberOfLoops && !stopRequested(); ++i) {
// blocking calls...
QCoreApplication::processEvents(); // gives a chance for queued requestStop() call to be invoked
}
}
private:
inline bool stopRequested() {
QReadLocker lock(&m_flagMutex);
return m_bStopRequested;
}
bool m_bStopRequested = false;
QReadWriteLock m_flagMutex;
};

Qt library design with signals

I am trying to design a Qt library which gives the output back to the client code using signals, but I can't quite get my head around it, I think something is wrong.
Say the library exposes a single class A as follows:
class A {
public:
void request(int data);
signals:
void response(int res);
}
So the client code instantiates an A, connects its signal to a slot, and calls request(). I initially chose to use a signal to return the output because A takes some time to elaborate the response, so I want that call to be non-blocking.
My problem is: what if I need to call request() in many different places in my code, and do different things after I receive my response? I think the question is fundamentally on the correct use of signal/slot design of Qt.
To give a concrete example, and hopefully explain myself further, I temporarily solved the issue setting a boolean before the request() to "remind" me what path of execution to take later:
void doingThis() {
doingThis = true;
request(data);
}
...
void doingThat() {
doingThis = false;
request(data);
}
...
public mySlot(int res) {
if (dointThis) {
...
} else {
...
}
}
This is hideous. What am I doing wrong?
I agree with Ludo who commented on your question.
If you pass some random number (identifier) into the request, then A can emit that same random number back with the response signal. Even if you have a bunch of slots connected to that signal, you would make them only handle the signal if the identifier was familiar to them.
class A {
public:
void request(int data, int id);
signals:
void response(int res, int id);
}
void doingThis() {
request(data, 0xaaaa);
}
...
void doingThat() {
request(data, 0xbbbb);
}
...
public mySlotA(int res, int id) {
if (id == 0xaaaa) {
...
}
}
public mySlotB(int res, int id) {
if (id == 0xbbbb) {
...
}
}
In the case above, the id is hard-coded to represent where the call came from. However, you could also randomly generate the ID. If you did that, then you'd need to save the randomly generated ID. The advantage is that you could send several different requests from doingThis() and be able to understand which response belongs to each request when they arrive back in your slot.

How to define a static pointer to a class in MQL?

I've got the following MQL code:
class Collection {
public: void *Get(void *_object) { return NULL; }
};
class Timer {
protected:
string name;
uint start, end;
public:
void Timer(string _name = "") : name(_name) { };
void TimerStart() { start = GetTickCount(); }
void TimerStop() { end = GetTickCount(); }
};
class Profiler {
public:
static Collection *timers;
static ulong min_time;
void Profiler() { };
void ~Profiler() { Deinit(); };
static void Deinit() { delete Profiler::timers; };
};
// Initialize static global variables.
Collection *Profiler::timers = new Collection();
ulong Profiler::min_time = 1;
void main() {
// Define local variable.
static Timer *_timer = new Timer(__FUNCTION__); // This line doesn't.
//Timer *_timer = new Timer(__FUNCTION__); // This line works.
// Start a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStart();
/* Some code here. */
// Stop a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStop();
}
which defines a Timer class which is used as a timer to profile the functions how long it took. The original version uses a list of timers to store time separately on each call, however, the code has been simplified to provide a minimum working example and focus on the actual compilation problem.
The problem is when I'm using the following line in order to initialize a static variable:
static Timer *_timer = new Timer(__FUNCTION__); // Line 30.
the compilation fails with:
'Timer' - local variables cannot be used TestProfiler.mqh 30 30
When I drop static word, the code compiles fine.
But it doesn't help me, as I want to define this variable as a static pointer to the class, as I don't want to destroy my object each time when the same function is called over and over again, so the timers can be added to the list which can be read later on. I don't really see why the MQL compiler would prevent from compiling the above code. I also believe this syntax worked fine in the previous builds.
I'm using MetaEditor 5.00 build 1601 (May 2017).
What is wrong with my static variable declaration and how can I correct it, so it can point to a Timer class?
Keyword static has two different meanings in MQL4/5: it indicates that a member of a class is static (which is obvious), and it also says that a variable is static... for instance, if you have a variable that is used only in one function, you probably do not need to declare it globally but as a static. You can find an example of isNewBar() function that has static datetime lastBar=0; in the articles about new bar at mql5.com. This keyword in such a function says that the variable is not deleted after function is finished, but remains in memory and is used with the next call. And if you need a variable in OnTick() function - it does not make sence to have it static, declare it globally.

QTimer timeout and QMutex interaction

Let's say we have some basic timer and a slot which is invoked periodically.
SomeObject::SomeObject()
{
QTimer *timer = new QTimer;
connect(timer , SIGNAL(timeout()), this, SLOT(updateState()));
}
void SomeObject::updateState()
{
// some operations leading to update of updatedValue
}
I also have function from same object which forces updates and returns some value.
bool SomeObject::getLatestState()
{
updateState();
return updatedValue;
}
This function may be directly called from different threads. This brings question of thread safety to mind. Simple mutex lock in getLatestState will not help as in some rare cases getLatestState is called from another thread that starts updateState. And at the same time timer's timeout may occur. Can you help me handle this situation properly?
QMutexLocker can be used in such situations
this my exampl
static QMutex mainMutex;
.....
MainController* MainController::s_instance = NULL;
.....
MainController* MainController::getInstance()
{
if(!s_instance){
QMutexLocker lock(&mainMutex);
if(!s_instance){
s_instance = new MainController;
}
}
return s_instance;
}
getInstance() function directly called from different threads.

Blocking a Qt application during downloading a short file

I'm writing an application using Qt4.
I need to download a very short text file from a given http address.
The file is short and is needed for my app to be able to continue, so I would like to make sure the download is blocking (or will timeout after a few seconds if the file in not found/not available).
I wanted to use QHttp::get(), but this is a non-blocking method.
I thought I could use a thread : my app would start it, and wait for it to finish. The thread would handle the download and quit when the file is downloaded or after a timeout.
But I cannot make it work :
class JSHttpGetterThread : public QThread
{
Q_OBJECT
public:
JSHttpGetterThread(QObject* pParent = NULL);
~JSHttpGetterThread();
virtual void run()
{
m_pHttp = new QHttp(this);
connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool)));
m_pHttp->setHost("127.0.0.1");
m_pHttp->get("Foo.txt", &m_GetBuffer);
exec();
}
const QString& getDownloadedFileContent() const
{
return m_DownloadedFileContent;
}
private:
QHttp* m_pHttp;
QBuffer m_GetBuffer;
QString m_DownloadedFileContent;
private slots:
void onRequestFinished(int Id, bool Error)
{
m_DownloadedFileContent = "";
m_DownloadedFileContent.append(m_GetBuffer.buffer());
}
};
In the method creating the thread to initiate the download, here is what I'm doing :
JSHttpGetterThread* pGetter = new JSHttpGetterThread(this);
pGetter->start();
pGetter->wait();
But that doesn't work and my app keeps waiting. It looks lit the slot 'onRequestFinished' is never called.
Any idea ?
Is there a better way to do what I'm trying to do ?
Instead of using a thread you can just go into a loop which calls processEvents:
while (notFinished) {
qApp->processEvents(QEventLoop::WaitForMore | QEventLoop::ExcludeUserInput);
}
Where notFinished is a flag which can be set from the onRequestFinished slot.
The ExcludeUserInput will ensure that GUI related events are ignored while waiting.
A little late but:
Do not use these wait loops, the correct way is to use the done() signal from QHttp.
The requestFinished signal from what I have seen is just for when your application has finished the request, the data may still be on its way down.
You do not need a new thread, just setup the qhttp:
httpGetFile= new QHttp();
connect(httpGetFile, SIGNAL(done(bool)), this, SLOT(processHttpGetFile(bool)));
Also do not forget to flush the file in processHttpGetFile as it might not all be on the disk.
you have to call QThread::quit() or exit() if you are done - otherwise your thread will run forever...
I chose to implement David's solution, which seemed to be the easiest.
However, I had handle a few more things :
I had to adapt the QEventLoop enum values for Qt4.3.3 (the version I'm using);
I had to track the request Id, to make sure to exit the while loop when the download request is finished, and not when another request is finished;
I added a timeout, to make sure to exit the while loop if there is any problem.
Here is the result as (more or less) pseudo-code :
class BlockingDownloader : public QObject
{
Q_OBJECT
public:
BlockingDownloaderBlockingDownloader()
{
m_pHttp = new QHttp(this);
connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool)));
}
~BlockingDownloader()
{
delete m_pHttp;
}
QString getFileContent()
{
m_pHttp->setHost("www.xxx.com");
m_DownloadId = m_pHttp->get("/myfile.txt", &m_GetBuffer);
QTimer::singleShot(m_TimeOutTime, this, SLOT(onTimeOut()));
while (!m_FileIsDownloaded)
{
qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
}
return m_DownloadedFileContent;
}
private slots:
void BlockingDownloader::onRequestFinished(int Id, bool Error)
{
if (Id == m_DownloadId)
{
m_DownloadedFileContent = "";
m_DownloadedFileContent.append(m_GetBuffer.buffer());
m_FileIsDownloaded = true;
}
}
void BlockingDownloader::onTimeOut()
{
m_FileIsDownloaded = true;
}
private:
QHttp* m_pHttp;
bool m_FileIsDownloaded;
QBuffer m_GetBuffer;
QString m_DownloadedFileContent;
int m_DownloadId;
};
I used QNetworkAccsessManager for same necessity. Because this class managing connections RFC base (6 proccess same time) and non-blocking.
http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html
How about giving the GUI some amount of time to wait on the thread and then give up.
Something like:
JSHttpGetterThread* pGetter = new JSHttpGetterThread(this);
pGetter->start();
pGetter->wait(10000); //give the thread 10 seconds to download
Or...
Why does the GUI thread have to wait for the "downloader thread" at all? When the app fires up create the downloader thread, connect the finished() signal to some other object, start the downloader thread, and return. When the thread has finished, it will signal the other object which can resume your process.

Resources