Re: Thread and C++
peter koch wrote:
First let me state that I believe that you are aware that volatile has
no purpose in a multithreaded environment. Using a mutex is necessary
and sufficient in C++ (for C++0x other solutions will be available).
Of course, there might be buggy compilers out there that do not behave
well with optimizations but behave properly when using volatile, but
this is the first time I've heard about such a case. Do they provide
more information?
The book that mentions this is:
"C++ GUI Programming with Qt 4 (2nd Edition) - The official C++/Qt book":
http://www.qtsoftware.com/developer/books/cpp-gui-programming-with-qt-4-2nd-edition
They also use the style:
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
return app.exec();
}
while I use the style:
#include <cstdlib>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
if(app.exec()!= 0)
return EXIT_FAILURE;
}
and I thought, I should check out.
Regarding volatiles, in multithreading chapter (Chapter14) the books mentions:
"class Thread: public QThread
{
Q_OBJECT
public:
Thread();
void setMessage(const QString &message);
void stop();
protected:
void run();
private:
QString messageStr;
volatile bool stopped;
};
The Thread class is derived from QThread and reimplements the run() function. It provides two additional
functions: setMessage() and stop().
The stopped variable is declared volatile because it is accessed from different threads and we want to be sure
that it is freshly read every time it is needed. If we omitted the volatile keyword, the compiler might
optimize access to the variable, possibly leading to incorrect results".