PDA

View Full Version : Why is this thread not running?



Cruz
25th December 2017, 13:53
Hi there. Below is the source of a simple example where I start a thread that spins in an infinite loop, and watches if a global variable frameIdx has changed its value. I start the thread in the main function, wait a bit, and then increment the frameIdx in the main function and the thread has to notice that the value has changed. Like so:



#include <QtConcurrent/QtConcurrent>
#include <QDebug>

int frameIdx = 0; // globally accessible variable

void work()
{
qDebug() << "Worker thread started.";

int idx = 0;
while(true)
{
qDebug() << "Thread" << counter << "frame idx" << idx << frameIdx; // This line makes the difference.

if (frameIdx > idx) // frameIdx has changed
{
qDebug() << "THREAD: increment frame idx" << idx << frameIdx;
idx = frameIdx;
}
}
}


int main(int argc, char *argv[])
{
qDebug() << "Starting thread";
QFuture<void> result = QtConcurrent::run(&work);

QThread::sleep(1); // Wait a little.

frameIdx++;
qDebug() << "MAIN: frame idx incremented" << frameIdx;

return 0;
}



This works as long as the qDebug() call in line 13 is enabled. Then, the thread writes something into the console in every iteration and eventually it tells me that the global variable has been incremented. If I comment the qDebug() line out, the thread is still started, I can see the "Worker thread started." message in the console, but the increment of the frameIdx is never reported. It seems that the worker thread is not running after all. Can anyone please explain to me what's happening?

Thank you,
Cruz

Cruz
25th December 2017, 18:36
Aaah, I get it. The compiler optimizes my thread away since it can't see that frameIdx will ever change its value. Declaring it

volatile int frameIdx = 0;
Does the trick.