Re: Thread and C++
On 30 Mar., 22:16, Ioannis Vranos <ivra...@freemail.gr> wrote:
peter koch wrote:
[snip]
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...
[snip]
Regarding volatiles, in multithreading chapter (Chapter14) the books ment=
ions:
"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() funct=
ion. It provides two additional
functions: setMessage() and stop().
The stopped variable is declared volatile because it is accessed from dif=
ferent threads and we want to be sure
that it is freshly read every time it is needed. If we omitted the volati=
le keyword, the compiler might
optimize access to the variable, possibly leading to incorrect results".
That is clearly wrong: if the boolean "stopped" is modified using a
mutex only, there is no need for the volatile. What might happen is
that stopped is not modified under the control of a mutex: if the only
change that might take place is a change from false to true, it is my
understanding that such a change will be safe. And even if there might
be perverted situations where this might not be the case, I am
confident that no implementation ever would behave like that.
If we assume that stopped is accessed without using a mutex, it is
possible that the value written by one thread will never propagate to
another. The problem just is that this will not change with volatile.
/Peter